wxUtil.php 65 KB

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