wxUtil.php 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  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. $arr = json_decode($response);
  502. return $arr;
  503. }
  504. /**
  505. * 创建模板消息
  506. */
  507. public static function tMessageCreate($merchant, $shortTemplateId, $isOpen = 0)
  508. {
  509. $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen);
  510. $url = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={$accessToken}";
  511. $post = array('template_id_short' => $shortTemplateId);
  512. $curl = new curl\Curl();
  513. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  514. $result = Json::decode($result);
  515. return $result;
  516. }
  517. /**
  518. * 删除模板消息
  519. */
  520. public static function delTMessage($merchant, $templateId, $isOpen)
  521. {
  522. $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen);
  523. $url = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token={$accessToken}";
  524. $post = array('template_id' => $templateId);
  525. $curl = new curl\Curl();
  526. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  527. $result = Json::decode($result);
  528. return $result;
  529. }
  530. /**
  531. * 取所有模板消息
  532. */
  533. public function getAllTMessage($merchant)
  534. {
  535. $accessToken = self::getAuthorizerAccessToken($merchant);
  536. $url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={$accessToken}";
  537. $curl = new curl\Curl();
  538. $result = $curl->get($url);
  539. $result = Json::decode($result);
  540. return $result;
  541. }
  542. /**
  543. * 设置模板消息的行业
  544. */
  545. public function setTMIndustry($merchant, $industry_id1, $industry_id2)
  546. {
  547. $accessToken = self::getAuthorizerAccessToken($merchant);
  548. $url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={$accessToken}";
  549. $post = array('industry_id1' => $industry_id1, 'industry_id2' => $industry_id2);
  550. $curl = new curl\Curl();
  551. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  552. $result = Json::decode($result);
  553. return $result;
  554. }
  555. /**
  556. * 获取公众号的accessToken 公众号调用凭据
  557. */
  558. public static function getAuthorizerAccessToken($merchant, $isOpen = 0)
  559. {
  560. $sjId = $merchant['id'];
  561. $open = [];
  562. if ($isOpen == 1) {
  563. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  564. }
  565. if ($isOpen == 2) {
  566. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  567. }
  568. if ($isOpen == 3) {
  569. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  570. }
  571. if (empty($open)) {
  572. util::fail('没有找到平台信息');
  573. }
  574. $component_app_id = $open['appId'];
  575. $componentAccessToken = wxUtil::getComponentAccessToken($open);
  576. $appId = $merchant['wxAppId'];
  577. $wxAccessToken = $merchant['wxAccessToken'];
  578. $wxAccessTokenTime = $merchant['wxAccessTokenTime'];
  579. $authorize_refresh_token = $merchant['wxRefreshToken'];
  580. $now = time();
  581. if ($now > strtotime($wxAccessTokenTime)) {
  582. $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$componentAccessToken}";
  583. $data = ['component_appid' => $component_app_id, 'authorizer_appid' => $appId, 'authorizer_refresh_token' => $authorize_refresh_token];
  584. $curl = new curl\Curl();
  585. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  586. Yii::info('通过refresh_token获取access_token返回:' . $result);
  587. $result = Json::decode($result);
  588. if (isset($result['authorizer_access_token'])) {
  589. $wxAccessToken = $result['authorizer_access_token'];
  590. $expires_in = $result['expires_in'];
  591. $authorize_refresh_token = $result['authorizer_refresh_token'];
  592. $uData['wxRefreshToken'] = $authorize_refresh_token;;
  593. $uData['wxAccessToken'] = $wxAccessToken;
  594. $uData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  595. if (in_array($isOpen, [1, 2, 3])) {
  596. //零售、供货商和商城
  597. $wxBaseId = $open['wxBaseId'] ?? 0;
  598. if (!empty($wxBaseId)) {
  599. WxBaseService::updateById($wxBaseId, $uData);
  600. }
  601. } else {
  602. //其它
  603. xhMerchantService::updateById($sjId, $uData);
  604. }
  605. } else {
  606. noticeUtil::push("access_token已经失效,并且通过refresh_token没有获取到新的token isOpen:{$isOpen}。返回:" . json_encode($result), '15280215347');
  607. }
  608. }
  609. Yii::info('获取componentAccessToken 成功:' . $componentAccessToken);
  610. return $wxAccessToken;
  611. }
  612. /**
  613. * 获取小程序的accessToken
  614. */
  615. public static function getMiniProgramAccessToken($merchant, $isOpen = 0)
  616. {
  617. $sjId = isset($merchant['id']) ? $merchant['id'] : 0;
  618. $open = [];
  619. if ($isOpen == 1) {
  620. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  621. } elseif ($isOpen == 2) {
  622. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  623. } elseif ($isOpen == 3) {
  624. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  625. } else {
  626. util::fail('没有找到平台');
  627. }
  628. $component_app_id = $open['appId'];
  629. $componentAccessToken = wxUtil::getComponentAccessToken($open);
  630. $appId = $merchant['miniAppId'];
  631. if ($isOpen == 1) {
  632. $miniAccessToken = $merchant['miniAccessToken'];
  633. $miniAccessTokenTime = $merchant['miniAccessTokenTime'];
  634. $miniRefreshToken = $merchant['miniRefreshToken'];
  635. } elseif ($isOpen == 2) {
  636. $miniAccessToken = $merchant['miniAccessToken'];
  637. $miniAccessTokenTime = $merchant['miniAccessTokenTime'];
  638. $miniRefreshToken = $merchant['miniRefreshToken'];
  639. } elseif ($isOpen == 3) {
  640. $miniAccessToken = $merchant['miniAccessToken'];
  641. $miniAccessTokenTime = $merchant['miniAccessTokenTime'];
  642. $miniRefreshToken = $merchant['miniRefreshToken'];
  643. } else {
  644. $extend = xhMerchantExtendService::getBySjId($sjId);
  645. $miniAccessToken = $extend['miniAccessToken'];
  646. $miniAccessTokenTime = $extend['miniAccessTokenTime'];
  647. $miniRefreshToken = $extend['miniRefreshToken'];
  648. }
  649. $now = time();
  650. Yii::info("当前时间:{$now} 小程序accessToken过期时间:" . strtotime($miniAccessTokenTime) . " merchant:" . json_encode($merchant));
  651. if ($now > strtotime($miniAccessTokenTime)) {
  652. $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$componentAccessToken}";
  653. $data = ['component_appid' => $component_app_id, 'authorizer_appid' => $appId, 'authorizer_refresh_token' => $miniRefreshToken];
  654. $curl = new curl\Curl();
  655. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  656. $result = Json::decode($result);
  657. Yii::info('重新获取mini accesstoken:' . json_encode($result));
  658. if (isset($result['authorizer_access_token'])) {
  659. $expires_in = $result['expires_in'];
  660. $miniAccessToken = $result['authorizer_access_token'];
  661. $uData['miniRefreshToken'] = $result['authorizer_refresh_token'];
  662. $uData['miniAccessToken'] = $miniAccessToken;
  663. $uData['miniAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  664. if ($isOpen == 1) {
  665. $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0;
  666. if (!empty($wxMiniBaseId)) {
  667. WxMiniBaseService::updateById($wxMiniBaseId, $uData);
  668. }
  669. } elseif ($isOpen == 2) {
  670. $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0;
  671. if (!empty($wxMiniBaseId)) {
  672. WxMiniBaseService::updateById($wxMiniBaseId, $uData);
  673. }
  674. } elseif ($isOpen == 3) {
  675. $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0;
  676. if (!empty($wxMiniBaseId)) {
  677. WxMiniBaseService::updateById($wxMiniBaseId, $uData);
  678. }
  679. } else {
  680. xhMerchantExtendService::updateBySjId($sjId, $uData);
  681. }
  682. return $miniAccessToken;
  683. }
  684. Yii::info('accessToken失效:sjId:' . $sjId);
  685. }
  686. Yii::info('有效小程序 accesstoken:' . $miniAccessToken);
  687. return $miniAccessToken;
  688. }
  689. public static function saveWeixinImg($userId, $url, $class = 0)
  690. {
  691. $className = [
  692. '0' => 'weixinUserAvatar',//微信头像
  693. '1' => 'weixinUserImg',//微信公众号二维码
  694. '2' => 'weixinMpQrcode',
  695. '3' => 'weixinMpAvatar',
  696. ];
  697. $folder = Yii::getAlias('@webroot') . '/../../images';
  698. $pre = '/' . $className[$class] . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  699. if (!file_exists($folder . $pre))
  700. mkdir($folder . $pre, 0777, true);
  701. $randString = stringUtil::buildOrderNo();
  702. $name = md5($userId . $randString) . '.jpg';
  703. $fullFileName = $folder . $pre . $name;
  704. $fileName = $pre . $name;
  705. $curl = new curl\Curl();
  706. $result = $curl->get($url);
  707. $fp2 = @fopen($fullFileName, 'a');//文件大小
  708. fwrite($fp2, $result);
  709. fclose($fp2);
  710. return $fileName;
  711. }
  712. /**
  713. * 下载学员作品图片
  714. */
  715. public static function downloadStudentWorksImg($merchant, $mediaId, $savePathType = 'wxUserImg')
  716. {
  717. $accessToken = self::getAuthorizerAccessToken($merchant);
  718. $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$mediaId}";
  719. $ch = curl_init($url);
  720. curl_setopt($ch, CURLOPT_HEADER, 0);
  721. curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出。
  722. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  723. $body = curl_exec($ch);
  724. $httpinfo = curl_getinfo($ch);
  725. curl_close($ch);
  726. preg_match('/\w\/(\w+)/i', $httpinfo["content_type"], $extmatches);//求出文件格式
  727. $fileExt = $extmatches[1];
  728. $imgSavePath = dict::getDict('imgSavePath');
  729. $comImgSavePath = $imgSavePath[$savePathType];
  730. $folder = Yii::getAlias('@webroot') . '/../../images';
  731. $pre = '/' . $comImgSavePath . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  732. if (!file_exists($folder . $pre)) {
  733. mkdir($folder . $pre, 0777, true);
  734. }
  735. $randString = stringUtil::buildOrderNo();
  736. $fullFileName = $folder . $pre . $randString . '.jpg';
  737. $fileName = $pre . $randString . '.jpg';
  738. $fp2 = @fopen($fullFileName, 'a');//文件大小
  739. fwrite($fp2, $body);
  740. fclose($fp2);
  741. $srcImg = $fullFileName;
  742. $dstImg300 = $folder . $pre . $randString . "_300.jpg";//生成300px缩略图,不保存到数据库
  743. util::img2thumb($srcImg, $dstImg300, $width = 300, 0, 0, 0);
  744. $dstImg100 = $folder . $pre . $randString . "_100.jpg";//生成50px缩略图,不保存到数据库
  745. util::img2thumb($srcImg, $dstImg100, $width = 100, 0, 0, 0);
  746. return $fileName;
  747. }
  748. /**
  749. * 获取media_id里的图片保存到服务器
  750. */
  751. public static function downloadmediaIdImg($merchant, $mediaId, $savePathType = 'wxUserImg')
  752. {
  753. $accessToken = self::getAuthorizerAccessToken($merchant);
  754. $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$mediaId}";
  755. $ch = curl_init($url);
  756. curl_setopt($ch, CURLOPT_HEADER, 0);
  757. curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出。
  758. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  759. $body = curl_exec($ch);
  760. $httpinfo = curl_getinfo($ch);
  761. curl_close($ch);
  762. preg_match('/\w\/(\w+)/i', $httpinfo["content_type"], $extmatches);//求出文件格式
  763. $fileExt = $extmatches[1];
  764. $imgSavePath = dict::getDict('imgSavePath');
  765. $comImgSavePath = $imgSavePath[$savePathType];
  766. $folder = Yii::getAlias('@webroot') . '/../../images';
  767. $pre = '/' . $comImgSavePath . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  768. if (!file_exists($folder . $pre)) {
  769. mkdir($folder . $pre, 0777, true);
  770. }
  771. $randString = stringUtil::buildOrderNo();
  772. $fullFileName = $folder . $pre . $randString . '.jpg';
  773. $fileName = $pre . $randString . '.jpg';
  774. $fp2 = @fopen($fullFileName, 'a');//文件大小
  775. fwrite($fp2, $body);
  776. fclose($fp2);
  777. $srcImg = $fullFileName;
  778. $mediumImg = $pre . $randString . "_200.jpg";
  779. $dstImg200 = $folder . $mediumImg;//生成200px缩略图,不保存到数据库
  780. util::img2thumb($srcImg, $dstImg200, $width = 200, 0, 0, 0);
  781. $smallImg = $pre . $randString . "_50.jpg";
  782. $dstImg50 = $folder . $smallImg;//生成50px缩略图,不保存到数据库
  783. util::img2thumb($srcImg, $dstImg50, $width = 50, 0, 0, 0);
  784. return ['large' => $fileName, 'medium' => $mediumImg, 'small' => $smallImg];
  785. }
  786. public static function createTag($merchant, $name)
  787. {
  788. $accessToken = self::getAuthorizerAccessToken($merchant);
  789. $url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token={$accessToken}";
  790. $post = ['tag' => ['name' => $name]];
  791. $curl = new curl\Curl();
  792. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  793. $result = Json::decode($result);
  794. return $result;
  795. }
  796. public static function delTag($merchant, $id)
  797. {
  798. $accessToken = self::getAuthorizerAccessToken($merchant);
  799. $url = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={$accessToken}";
  800. $post = ['tag' => ['id' => $id]];
  801. $curl = new curl\Curl();
  802. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  803. $result = Json::decode($result);
  804. return $result;
  805. }
  806. public static function modTag($merchant, $id, $name)
  807. {
  808. $accessToken = self::getAuthorizerAccessToken($merchant);
  809. $url = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token={$accessToken}";
  810. $post = ['tag' => ['id' => $id, 'name' => $name]];
  811. $curl = new curl\Curl();
  812. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  813. $result = Json::decode($result);
  814. return $result;
  815. }
  816. /**
  817. * 获取商家所有标签
  818. */
  819. public static function getTag($merchant)
  820. {
  821. $accessToken = self::getAuthorizerAccessToken($merchant);
  822. $url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token={$accessToken}";
  823. $curl = new curl\Curl();
  824. $result = $curl->get($url);
  825. $result = Json::decode($result);
  826. return $result;
  827. }
  828. public function getUserTag($tagId, $nextOpenId = '')
  829. {
  830. $url = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=" . $this->access_token;
  831. $post = ['tagid' => $tagId, 'next_openid' => $nextOpenId];
  832. $curl = new curl\Curl();
  833. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  834. $result = Json::decode($result);
  835. return $result;
  836. }
  837. /**
  838. * 批量为用户打标签
  839. */
  840. public static function membersBatchTag($merchant, $openIdList, $tagId)
  841. {
  842. $accessToken = self::getAuthorizerAccessToken($merchant);
  843. $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={$accessToken}";
  844. $post = ['openid_list' => $openIdList, 'tagid' => $tagId];
  845. $curl = new curl\Curl();
  846. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  847. $result = Json::decode($result);
  848. return $result;
  849. }
  850. /**
  851. * 批量取消用户标签
  852. */
  853. public static function membersCancelTag($merchant, $openIdList, $tagId)
  854. {
  855. $accessToken = self::getAuthorizerAccessToken($merchant);
  856. $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={$accessToken}";
  857. $post = ['openid_list' => $openIdList, 'tagid' => $tagId];
  858. $curl = new curl\Curl();
  859. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  860. $result = Json::decode($result);
  861. return $result;
  862. }
  863. /**
  864. * 新增临时素材
  865. */
  866. public static function uploadTempMedia($merchant, $imgUrl, $type = 'image')
  867. {
  868. $accessToken = self::getAuthorizerAccessToken($merchant);
  869. $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$accessToken}&type=" . $type;
  870. $postData = ['media' => '@' . $imgUrl];
  871. $ch = curl_init();
  872. curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
  873. curl_setopt($ch, CURLOPT_URL, $url);
  874. curl_setopt($ch, CURLOPT_POST, 1);
  875. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  876. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  877. $response = curl_exec($ch);
  878. $result = Json::decode($response);
  879. return $result;
  880. }
  881. /**
  882. * 获取临时素材
  883. */
  884. public static function getTempMaterial($merchant, $mediaId)
  885. {
  886. $accessToken = self::getAuthorizerAccessToken($merchant);
  887. $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id=" . $mediaId;
  888. $fileInfo = self::getTempMaterialInfo($url);
  889. if (empty($fileInfo) || isset($fileInfo['errcode'])) {
  890. $msg = '未错误哦~';
  891. return ['code' => 'A0002', 'msg' => $msg];
  892. }
  893. $fileName = substr(md5($mediaId), -4) . stringUtil::buildOrderNo() . '.amr';
  894. $preFolder = Yii::getAlias('@webroot') . '/../../images';
  895. $folder = '/weixinChatVoice/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  896. if (!file_exists($preFolder . $folder))
  897. mkdir($preFolder . $folder, 0777, true);
  898. $saveFile = $preFolder . $folder . $fileName;
  899. if (file_exists($saveFile) == false) {
  900. self::readTempMaterial($saveFile, $fileInfo["body"]);
  901. }
  902. return ['code' => 'A0001', 'msg' => 'success', 'data' => ['url' => $folder . $fileName]];
  903. }
  904. /**
  905. * 获取临时素材的头信息等
  906. */
  907. public static function getTempMaterialInfo($url)
  908. {
  909. $ch = curl_init($url);
  910. curl_setopt($ch, CURLOPT_HEADER, 0);
  911. curl_setopt($ch, CURLOPT_NOBODY, 0);//只取body头
  912. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  913. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  914. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  915. $package = curl_exec($ch);
  916. $httpinfo = curl_getinfo($ch);
  917. curl_close($ch);
  918. $imageAll = ['header' => $httpinfo, 'body' => $package];
  919. return $imageAll;
  920. }
  921. /**
  922. * 读取临时素材的资源
  923. */
  924. function readTempMaterial($filename, $fileContent)
  925. {
  926. $localFile = fopen($filename, 'w');
  927. if (false !== $localFile) {
  928. if (false !== fwrite($localFile, $fileContent)) {
  929. fclose($localFile);
  930. }
  931. }
  932. }
  933. /**
  934. * 创建门店
  935. */
  936. public function createStore($info)
  937. {
  938. $jsonData = urldecode(json_encode($info, JSON_UNESCAPED_UNICODE));
  939. $url = "http://api.weixin.qq.com/cgi-bin/poi/addpoi?access_token=" . $this->access_token;
  940. $curl = new curl\Curl();
  941. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  942. }
  943. /**
  944. * 查询门店信息
  945. */
  946. public function getStoreInfo($poi_id)
  947. {
  948. $data = ['poi_id' => $poi_id];
  949. $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  950. $url = "http://api.weixin.qq.com/cgi-bin/poi/getpoi?access_token=" . $this->access_token;
  951. $curl = new curl\Curl();
  952. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  953. }
  954. /**
  955. * 查询门店列表
  956. */
  957. public function getStoreList($begin = 0, $count = 20)
  958. {
  959. $data = ["begin" => $begin, "limit" => $count];
  960. $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  961. $url = "http://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" . $this->access_token;
  962. $curl = new curl\Curl();
  963. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  964. }
  965. /**
  966. * 查询门店列表 -- 重复 可删除
  967. */
  968. function getShopList($data)
  969. {
  970. $url = "https://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" . $this->access_token;
  971. $curl = new curl\Curl();
  972. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  973. $result = Json::decode($result);
  974. return $result;
  975. }
  976. /**
  977. * 修改门店服务信息
  978. */
  979. public function updateStore(array $buffer)
  980. {
  981. $jsonData = urldecode(json_encode($buffer, JSON_UNESCAPED_UNICODE));
  982. $url = "http://api.weixin.qq.com/cgi-bin/poi/updatepoi?access_token=" . $this->access_token;
  983. $curl = new curl\Curl();
  984. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  985. }
  986. /**
  987. * 删除门店
  988. */
  989. public function delStore($poi_id)
  990. {
  991. $data = ['poi_id' => $poi_id];
  992. $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  993. $url = "http://api.weixin.qq.com/cgi-bin/poi/delpoi?access_token=" . $this->access_token;
  994. $curl = new curl\Curl();
  995. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  996. }
  997. /**
  998. * 门店类目表
  999. */
  1000. public function storeTypeList()
  1001. {
  1002. $url = "http://api.weixin.qq.com/cgi-bin/poi/getwxcategory?access_token=" . $this->access_token;
  1003. $curl = new curl\Curl();
  1004. return $curl->get($url);
  1005. }
  1006. /******************************* wifi *************************************/
  1007. /**
  1008. * 获取wifi门店列表
  1009. */
  1010. function getShopWifiList($pageindex = 1, $pagesize = 10)
  1011. {
  1012. $data = ["pageindex" => $pageindex, "pagesize" => $pagesize];
  1013. $url = "https://api.weixin.qq.com/bizwifi/shop/list?access_token=" . $this->access_token;
  1014. $curl = new curl\Curl();
  1015. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1016. $result = Json::decode($result);
  1017. return $result;
  1018. }
  1019. /**
  1020. * 添加密码型设备
  1021. */
  1022. function addPasswordDevice($shopId, $ssid, $pwd)
  1023. {
  1024. $data = ["shop_id" => $shopId, "ssid" => $ssid, "password" => $pwd];
  1025. $url = "https://api.weixin.qq.com/bizwifi/device/add?access_token=" . $this->access_token;
  1026. $curl = new curl\Curl();
  1027. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1028. $result = Json::decode($result);
  1029. return $result;
  1030. }
  1031. /**
  1032. * 修改门店Wi-Fi(修改门店网络信息)
  1033. */
  1034. function updateDevice($shopId, $oldSsid, $ssid, $pwd = '')
  1035. {
  1036. $data = ["shop_id" => $shopId, "old_ssid" => $oldSsid, "ssid" => $ssid];
  1037. if (!empty($pwd)) {
  1038. $data["password"] = $pwd;
  1039. }
  1040. $url = "https://api.weixin.qq.com/bizwifi/shop/update?access_token=" . $this->access_token;
  1041. $curl = new curl\Curl();
  1042. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1043. $result = Json::decode($result);
  1044. return $result;
  1045. }
  1046. /**
  1047. * 删除密码型设备
  1048. */
  1049. function delPasswordDevice($bssid)
  1050. {
  1051. $data = ["bssid" => $bssid];
  1052. $url = "https://api.weixin.qq.com/bizwifi/device/delete?access_token=" . $this->access_token;
  1053. $curl = new curl\Curl();
  1054. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1055. $result = Json::decode($result);
  1056. return $result;
  1057. }
  1058. /**
  1059. * 查询门店Wi-Fi信息
  1060. */
  1061. function getShopWifi($shopId)
  1062. {
  1063. $data = ["shop_id" => $shopId];
  1064. $url = "https://api.weixin.qq.com/bizwifi/shop/get?access_token=" . $this->access_token;
  1065. $curl = new curl\Curl();
  1066. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1067. $result = Json::decode($result);
  1068. return $result;
  1069. }
  1070. /**
  1071. * 获取物料二维码
  1072. */
  1073. function getWifiQrCode($shopId, $ssid, $img_id)
  1074. {
  1075. //$data = ["shop_id" => 429620, "ssid" => "WX567", "img_id" => $img_id];
  1076. $data = ["shop_id" => $shopId, "ssid" => $ssid, "img_id" => $img_id];
  1077. $url = "https://api.weixin.qq.com/bizwifi/qrcode/get?access_token=" . $this->access_token;
  1078. $curl = new curl\Curl();
  1079. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1080. $result = Json::decode($result);
  1081. return $result;
  1082. }
  1083. function getWifiUrl()
  1084. {
  1085. $url = "https://api.weixin.qq.com/bizwifi/account/get_connecturl?access_token=" . $this->access_token;
  1086. $curl = new curl\Curl();
  1087. $result = $curl->get($url);
  1088. $result = Json::decode($result);
  1089. return $result;
  1090. }
  1091. function generateShortUrl($longUrl)
  1092. {
  1093. $data = ["action" => "long2short", "long_url" => $longUrl,];
  1094. $url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" . $this->access_token;
  1095. $curl = new curl\Curl();
  1096. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1097. $result = Json::decode($result);
  1098. if (isset($result['errcode']) && $result['errcode'] == 0) {
  1099. return ['code' => 'A0001', 'data' => ['shortUrl' => $result['short_url']]];
  1100. }
  1101. return ['code' => 'A0002', 'data' => []];
  1102. }
  1103. //长链接转短链接 ssh 2019.9.26
  1104. public static function urlLongToShort($longUrl, $merchant)
  1105. {
  1106. $accessToken = self::getMiniProgramAccessToken($merchant);
  1107. $data = ["action" => "long2short", "long_url" => $longUrl,];
  1108. $url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" . $accessToken;
  1109. $curl = new curl\Curl();
  1110. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1111. $result = Json::decode($result);
  1112. $url = '';
  1113. if (isset($result['errcode']) && $result['errcode'] == 0) {
  1114. $url = $result['short_url'];
  1115. }
  1116. return ['url' => $url];
  1117. }
  1118. /**
  1119. * 拉取门店所有的设备信息
  1120. */
  1121. public function getShopWifiListAll()
  1122. {
  1123. $startPage = 1;
  1124. $list = [];
  1125. while (true) {
  1126. $reList = $this->getShopWifiList($startPage, 20);
  1127. if ($startPage <= $reList['data']['pagecount']) {
  1128. $list = array_merge($list, $reList['data']['records']);
  1129. ++$startPage;
  1130. } else {
  1131. break;
  1132. }
  1133. }
  1134. return $list;
  1135. }
  1136. /**
  1137. * 通过 poi_id 从Wi-Fi门店列表中 获取 shopId
  1138. */
  1139. public function getShopId($poiId, $list = [])
  1140. {
  1141. if (empty($list)) {
  1142. $list = $this->getShopWifiListAll();
  1143. }
  1144. foreach ($list as $shop) {
  1145. if ($shop['poi_id'] == $poiId)
  1146. return (string)$shop['shop_id'];
  1147. }
  1148. return false;
  1149. }
  1150. //设置小程序服务器域名
  1151. public static function setDomain($merchant, $isOpen = 0)
  1152. {
  1153. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1154. $url = "https://api.weixin.qq.com/wxa/modify_domain?access_token=" . $accessToken;
  1155. $curl = new curl\Curl();
  1156. //零售
  1157. $currentHost = Yii::$app->params['hdHost'];
  1158. if ($isOpen == 2) {
  1159. //供货商
  1160. $currentHost = Yii::$app->params['ghsHost'];
  1161. }
  1162. if ($isOpen == 3) {
  1163. //供货商
  1164. $currentHost = Yii::$app->params['mallHost'];
  1165. }
  1166. $has = strpos($currentHost, 'https');
  1167. //如果不是https则换成https
  1168. if ($has === false) {
  1169. $currentHost = str_replace('http', 'https', $currentHost);
  1170. }
  1171. $socket = str_replace("https", "", $currentHost);
  1172. $socket = str_replace("http", "", $socket);
  1173. $data = [
  1174. "action" => "set",
  1175. "requestdomain" => [$currentHost],
  1176. "wsrequestdomain" => ['wss' . $socket],
  1177. "uploaddomain" => [$currentHost],
  1178. "downloaddomain" => [$currentHost],
  1179. ];
  1180. print_r($data);
  1181. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1182. $respond = Json::decode($result);
  1183. print_r($respond);
  1184. }
  1185. //设置业务域名
  1186. public static function setWebViewDomain($merchant, $isOpen = 0)
  1187. {
  1188. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1189. $url = "https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=" . $accessToken;
  1190. $curl = new curl\Curl();
  1191. //零售
  1192. $currentHost = Yii::$app->params['hdHost'];
  1193. if ($isOpen == 2) {
  1194. //供货商
  1195. $currentHost = Yii::$app->params['ghsHost'];
  1196. }
  1197. if ($isOpen == 3) {
  1198. //供货商
  1199. $currentHost = Yii::$app->params['mallHost'];
  1200. }
  1201. $has = strpos($currentHost, 'https');
  1202. //如果不是https则换成https
  1203. if ($has === false) {
  1204. $currentHost = str_replace('http', 'https', $currentHost);
  1205. }
  1206. $data = [
  1207. "action" => "set",
  1208. "webviewdomain" => [$currentHost],
  1209. ];
  1210. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1211. $respond = Json::decode($result);
  1212. print_r($respond);
  1213. }
  1214. //为授权的小程序帐号上传小程序代码
  1215. public static function miniCommit($merchant, $templateId, $isOpen = 0)
  1216. {
  1217. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1218. $url = 'https://api.weixin.qq.com/wxa/commit?access_token=' . $accessToken;
  1219. $curl = new curl\Curl();
  1220. $apiUrl = Yii::$app->params['mallHost'];
  1221. if ($isOpen == 1) {
  1222. $apiUrl = Yii::$app->params['hdHost'];
  1223. } elseif ($isOpen == 2) {
  1224. $apiUrl = Yii::$app->params['ghsHost'];
  1225. } elseif ($isOpen == 3) {
  1226. $apiUrl = Yii::$app->params['mallHost'];
  1227. }
  1228. $imgUrl = imgUtil::getPrefix();
  1229. //如果不是https则换成https
  1230. $has = strpos($apiUrl, 'https');
  1231. if ($has === false) {
  1232. $apiUrl = str_replace('http', 'https', $apiUrl);
  1233. }
  1234. $open = [];
  1235. if ($isOpen == 1) {
  1236. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  1237. }
  1238. if ($isOpen == 2) {
  1239. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  1240. }
  1241. if ($isOpen == 3) {
  1242. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  1243. }
  1244. if (empty($open)) {
  1245. util::fail('没有找到平台');
  1246. }
  1247. //如果不是https则换成https
  1248. $has = strpos($imgUrl, 'https');
  1249. if ($has === false) {
  1250. $imgUrl = str_replace('http', 'https', $imgUrl);
  1251. }
  1252. $account = isset($merchant['id']) ? $merchant['id'] : 0;
  1253. $name = isset($merchant['name']) ? $merchant['name'] : '';
  1254. if ($isOpen == 1) {
  1255. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  1256. $wxBase = WxBaseClass::getById($wxBaseId);
  1257. $name = isset($wxBase['name']) ? $wxBase['name'] : '';
  1258. } elseif ($isOpen == 2) {
  1259. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  1260. $wxBase = WxBaseClass::getById($wxBaseId);
  1261. $name = isset($wxBase['name']) ? $wxBase['name'] : '';
  1262. } elseif ($isOpen == 3) {
  1263. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  1264. $wxBase = WxBaseClass::getById($wxBaseId);
  1265. $name = isset($wxBase['name']) ? $wxBase['name'] : '';
  1266. }
  1267. $ext = [
  1268. 'extAppid' => $merchant['miniAppId'],
  1269. 'ext' => [
  1270. 'account' => $account,
  1271. 'apiHost' => $apiUrl,
  1272. 'imgHost' => $imgUrl,
  1273. 'name' => $name,
  1274. ],
  1275. ];
  1276. echo '<pre>';
  1277. print_r($ext);
  1278. Yii::info("ext:" . json_encode($ext));
  1279. $extJson = json_encode($ext);
  1280. $data = [
  1281. "template_id" => $templateId,
  1282. "ext_json" => $extJson,
  1283. "user_version" => date("mdHis"),
  1284. "user_desc" => date("mdHis")
  1285. ];
  1286. print_r($data);
  1287. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1288. $respond = Json::decode($result);
  1289. print_r($respond);
  1290. }
  1291. //获取体验小程序的体验二维码
  1292. public static function getExperienceQrCode($merchant, $page, $isOpen = 0)
  1293. {
  1294. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1295. $path = urlencode($page);
  1296. $url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token={$accessToken}&path=" . $path;
  1297. $curl = new curl\Curl();
  1298. $result = $curl->get($url);
  1299. $file = dirUtil::getImgDir() . 'retail/miniExperience/' . $merchant['id'] . '.jpg';
  1300. file_put_contents($file, $result);
  1301. //上传oss
  1302. $obj = 'retail/miniExperience/' . $merchant['id'] . '.jpg';
  1303. oss::uploadImage($obj, $file);
  1304. echo "<b /><img src='" . imgUtil::getPrefix() . "/retail/miniExperience/" . $merchant['id'] . ".jpg' />";
  1305. }
  1306. //获取授权小程序帐号已设置的类目
  1307. public static function getMiniCategory($merchant, $isOpen = 0)
  1308. {
  1309. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1310. $url = "https://api.weixin.qq.com/wxa/get_category?access_token=" . $accessToken;
  1311. $curl = new curl\Curl();
  1312. $result = $curl->get($url);
  1313. $respond = Json::decode($result);
  1314. echo "<pre>";
  1315. print_r($respond);
  1316. }
  1317. //小程序加急审核 ssh 2020.4.20
  1318. public static function speedupAudit($merchant, $id, $isOpen = 0)
  1319. {
  1320. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1321. $url = "https://api.weixin.qq.com/wxa/speedupaudit?access_token=" . $accessToken;
  1322. $curl = new curl\Curl();
  1323. $data = [
  1324. "auditid" => $id
  1325. ];
  1326. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1327. $respond = Json::decode($result);
  1328. print_r($respond);
  1329. }
  1330. //获取小程序的第三方提交代码的页面配置
  1331. public static function getMiniPage($merchant, $isOpen = 0)
  1332. {
  1333. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1334. $url = "https://api.weixin.qq.com/wxa/get_page?access_token=" . $accessToken;
  1335. $curl = new curl\Curl();
  1336. $result = $curl->get($url);
  1337. $respond = Json::decode($result);
  1338. echo "<pre>";
  1339. print_r($respond);
  1340. }
  1341. //将第三方提交的代码包提交审核
  1342. public static function miniSubmitAudit($merchant, $page, $isOpen = 0)
  1343. {
  1344. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1345. $url = "https://api.weixin.qq.com/wxa/submit_audit?access_token=" . $accessToken;
  1346. $curl = new curl\Curl();
  1347. $data = [
  1348. "item_list" => [
  1349. [
  1350. "address" => $page,
  1351. "tag" => "花卉宝 花店",
  1352. "first_class" => "IT科技",
  1353. "second_class" => "软件服务提供商",
  1354. "first_id" => 210,
  1355. "second_id" => 413,
  1356. "title" => "花卉宝",
  1357. ],
  1358. ],
  1359. "feedback_info" => "",
  1360. "feedback_stuff" => "",
  1361. "version_desc" => "右上角若有【体验】二字,点击可登陆后台体验",
  1362. ];
  1363. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1364. $respond = Json::decode($result);
  1365. echo "<pre>";
  1366. print_r($respond);
  1367. }
  1368. //查询最新一次提交的审核状态
  1369. public static function miniGetLatestAuditStatus($merchant, $isOpen = 0)
  1370. {
  1371. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1372. $url = "https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=" . $accessToken;
  1373. $curl = new curl\Curl();
  1374. $result = $curl->get($url);
  1375. $respond = Json::decode($result);
  1376. echo "<pre>";
  1377. print_r($respond);
  1378. }
  1379. //发布已通过审核的小程序
  1380. public static function miniRelease($merchant, $isOpen = 0)
  1381. {
  1382. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1383. $url = "https://api.weixin.qq.com/wxa/release?access_token=" . $accessToken;
  1384. $curl = new curl\Curl();
  1385. $result = $curl->setOption(CURLOPT_POSTFIELDS, '{}')->post($url);
  1386. $respond = Json::decode($result);
  1387. return $respond;
  1388. }
  1389. //撤回审核
  1390. public static function rollbackCheck($merchant, $isOpen = 0)
  1391. {
  1392. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1393. $url = "https://api.weixin.qq.com/wxa/undocodeaudit?access_token=" . $accessToken;
  1394. $curl = new curl\Curl();
  1395. $result = $curl->get($url);
  1396. $respond = Json::decode($result);
  1397. echo "<pre>";
  1398. print_r($respond);
  1399. }
  1400. //申请会员的小程序码
  1401. public static function generateMemberCode($merchant, $shopId, $isOpen = 0)
  1402. {
  1403. $fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
  1404. $behind = 'retail/mimiMemberCode/';
  1405. $filePath = dirUtil::getImgDir() . $behind;
  1406. if (!file_exists($filePath)) {
  1407. mkdir($filePath, 0777, true);
  1408. }
  1409. $file = $filePath . $fileName;
  1410. if (file_exists($file)) {
  1411. return $behind . $fileName;
  1412. }
  1413. $path = 'pages/home/user?scan=1&shopId=' . $shopId;
  1414. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1415. $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
  1416. $curl = new curl\Curl();
  1417. $data = [
  1418. "path" => $path,
  1419. "width" => 1000,
  1420. ];
  1421. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1422. file_put_contents($file, $result);
  1423. return $behind . $fileName;
  1424. }
  1425. //收款小程序码
  1426. public static function generateGatheringMiniCode($merchant, $shopId, $isOpen = 0)
  1427. {
  1428. $fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
  1429. $behind = 'retail/gatheringMimiCode/';
  1430. $filePath = dirUtil::getImgDir() . $behind;
  1431. if (!file_exists($filePath)) {
  1432. mkdir($filePath, 0777, true);
  1433. }
  1434. $file = $filePath . $fileName;
  1435. if (file_exists($file)) {
  1436. return $behind . $fileName;
  1437. }
  1438. $path = 'pages/pay/index?scan=1&shopId=' . $shopId;
  1439. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1440. $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
  1441. $curl = new curl\Curl();
  1442. $data = [
  1443. "path" => $path,
  1444. "width" => 1000,
  1445. ];
  1446. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1447. file_put_contents($file, $result);
  1448. return $behind . $fileName;
  1449. }
  1450. //微信开放平台获取component_access_token
  1451. public static function getComponentAccessToken($open)
  1452. {
  1453. $id = $open['id'];
  1454. $componentAccessToken = $open['componentAccessToken'];
  1455. $componentAccessTokenTime = $open['componentAccessTokenTime'];
  1456. $now = time();
  1457. if ($now > strtotime($componentAccessTokenTime)) {
  1458. $appId = $open['appId'];
  1459. $appSecret = $open['appSecret'];
  1460. $verifyTicket = $open['verifyTicket'];
  1461. $data = ['component_appid' => $appId, 'component_appsecret' => $appSecret, 'component_verify_ticket' => $verifyTicket];
  1462. $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
  1463. $curl = new curl\Curl();
  1464. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1465. if (empty($result)) {
  1466. util::stop('没有取到ComponentAccessToken');
  1467. }
  1468. $result = Json::decode($result);
  1469. if (isset($result['component_access_token']) == false || empty($result['component_access_token'])) {
  1470. echo '<pre>';
  1471. print_r($result);
  1472. Yii::info('get component access token error:' . json_encode($result));
  1473. Yii::$app->end();
  1474. }
  1475. $component_access_token = $result['component_access_token'];
  1476. $expiresIn = $result['expires_in'];
  1477. $oData = [];
  1478. $oData['componentAccessToken'] = $component_access_token;
  1479. $oData['componentAccessTokenTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短
  1480. xhWxOpenService::updateById($id, $oData);
  1481. return $component_access_token;
  1482. } else {
  1483. return $componentAccessToken;
  1484. }
  1485. }
  1486. /**
  1487. * 微信开放平台获取预授权码pre_auth_code
  1488. */
  1489. public static function getPreAuthCode($open)
  1490. {
  1491. $id = $open['id'];
  1492. $preAuthCode = $open['preAuthCode'];
  1493. $preAuthCodeTime = $open['preAuthCodeTime'];
  1494. $now = time();
  1495. if ($now > strtotime($preAuthCodeTime)) {
  1496. $token = self::getComponentAccessToken($open);
  1497. $appId = $open['appId'];
  1498. $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
  1499. $curl = new curl\Curl();
  1500. $data = ['component_appid' => $appId];
  1501. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1502. $result = Json::decode($result);
  1503. Yii::info($result);
  1504. if (isset($result['pre_auth_code']) == false || empty($result['pre_auth_code'])) {
  1505. echo "没有取到pre_auth_code,原因:" . json_encode($result) . " appid:" . $appId . " token:" . $token;
  1506. Yii::$app->end();
  1507. }
  1508. $preAuthCode = $result['pre_auth_code'];
  1509. $expiresIn = $result['expires_in'];
  1510. $oData = [];
  1511. $oData['preAuthCode'] = $preAuthCode;
  1512. $oData['preAuthCodeTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短100秒
  1513. xhWxOpenService::updateById($id, $oData);
  1514. return $preAuthCode;
  1515. } else {
  1516. return $preAuthCode;
  1517. }
  1518. }
  1519. /**
  1520. * 微信开放平台使用授权码换取公众号的接口调用凭据和授权信息
  1521. */
  1522. public static function getAuthorizer($code, $open)
  1523. {
  1524. $appId = $open['appId'];
  1525. $accessToken = self::getComponentAccessToken($open);
  1526. $url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$accessToken}";
  1527. $curl = new curl\Curl();
  1528. $data = ['authorization_code' => $code, 'component_appid' => $appId];
  1529. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1530. $result = Json::decode($result);
  1531. return $result;
  1532. }
  1533. //微信开放平台获取授权方的公众号帐号基本信息 ssh 2020.3.11
  1534. public static function getAuthorizerInfo($authorizeAppId, $open)
  1535. {
  1536. $appId = $open['appId'];
  1537. $accessToken = self::getComponentAccessToken($open);
  1538. $url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$accessToken}";
  1539. $curl = new curl\Curl();
  1540. $data = ['component_appid' => $appId, 'authorizer_appid' => $authorizeAppId];
  1541. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1542. $result = Json::decode($result);
  1543. return $result;
  1544. }
  1545. }