wxUtil.php 67 KB

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