wxUtil.php 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  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, $id, $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" => $id
  1342. ];
  1343. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1344. $respond = Json::decode($result);
  1345. print_r($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. $data = [
  1365. "item_list" => [
  1366. [
  1367. "address" => $page,
  1368. "tag" => "花卉宝 花店",
  1369. "first_class" => "IT科技",
  1370. "second_class" => "软件服务提供商",
  1371. "first_id" => 210,
  1372. "second_id" => 413,
  1373. "title" => "花卉宝",
  1374. ],
  1375. ],
  1376. "feedback_info" => "",
  1377. "feedback_stuff" => "",
  1378. "version_desc" => "体验码请填写:01231964,线上环境,小心操作哦,谢谢 ^_^",
  1379. ];
  1380. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1381. $respond = Json::decode($result);
  1382. echo "<pre>";
  1383. print_r($respond);
  1384. }
  1385. //查询最新一次提交的审核状态
  1386. public static function miniGetLatestAuditStatus($merchant, $isOpen = 0)
  1387. {
  1388. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1389. $url = "https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=" . $accessToken;
  1390. $curl = new curl\Curl();
  1391. $result = $curl->get($url);
  1392. $respond = Json::decode($result);
  1393. echo "<pre>";
  1394. print_r($respond);
  1395. }
  1396. //发布已通过审核的小程序
  1397. public static function miniRelease($merchant, $isOpen = 0)
  1398. {
  1399. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1400. $url = "https://api.weixin.qq.com/wxa/release?access_token=" . $accessToken;
  1401. $curl = new curl\Curl();
  1402. $result = $curl->setOption(CURLOPT_POSTFIELDS, '{}')->post($url);
  1403. $respond = Json::decode($result);
  1404. return $respond;
  1405. }
  1406. //撤回审核
  1407. public static function rollbackCheck($merchant, $isOpen = 0)
  1408. {
  1409. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1410. $url = "https://api.weixin.qq.com/wxa/undocodeaudit?access_token=" . $accessToken;
  1411. $curl = new curl\Curl();
  1412. $result = $curl->get($url);
  1413. $respond = Json::decode($result);
  1414. echo "<pre>";
  1415. print_r($respond);
  1416. }
  1417. //申请会员的小程序码
  1418. public static function generateMemberCode($merchant, $shopId, $isOpen = 0)
  1419. {
  1420. $fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
  1421. $behind = 'retail/mimiMemberCode/';
  1422. $filePath = dirUtil::getImgDir() . $behind;
  1423. if (!file_exists($filePath)) {
  1424. mkdir($filePath, 0777, true);
  1425. }
  1426. $file = $filePath . $fileName;
  1427. if (file_exists($file)) {
  1428. return $behind . $fileName;
  1429. }
  1430. $path = 'pages/home/user?scan=1&shopId=' . $shopId;
  1431. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1432. $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
  1433. $curl = new curl\Curl();
  1434. $data = [
  1435. "path" => $path,
  1436. "width" => 1000,
  1437. ];
  1438. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1439. file_put_contents($file, $result);
  1440. return $behind . $fileName;
  1441. }
  1442. //收款小程序码
  1443. public static function generateGatheringMiniCode($merchant, $shopId, $isOpen = 0)
  1444. {
  1445. $fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
  1446. $behind = 'retail/gatheringMimiCode/';
  1447. $filePath = dirUtil::getImgDir() . $behind;
  1448. if (!file_exists($filePath)) {
  1449. mkdir($filePath, 0777, true);
  1450. }
  1451. $file = $filePath . $fileName;
  1452. if (file_exists($file)) {
  1453. return $behind . $fileName;
  1454. }
  1455. $path = 'pages/pay/index?scan=1&shopId=' . $shopId;
  1456. $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
  1457. $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
  1458. $curl = new curl\Curl();
  1459. $data = [
  1460. "path" => $path,
  1461. "width" => 1000,
  1462. ];
  1463. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1464. file_put_contents($file, $result);
  1465. return $behind . $fileName;
  1466. }
  1467. //微信开放平台获取component_access_token
  1468. public static function getComponentAccessToken($open)
  1469. {
  1470. $id = $open['id'];
  1471. $componentAccessToken = $open['componentAccessToken'];
  1472. $componentAccessTokenTime = $open['componentAccessTokenTime'];
  1473. $now = time();
  1474. if ($now > strtotime($componentAccessTokenTime)) {
  1475. $appId = $open['appId'];
  1476. $appSecret = $open['appSecret'];
  1477. $verifyTicket = $open['verifyTicket'];
  1478. $data = ['component_appid' => $appId, 'component_appsecret' => $appSecret, 'component_verify_ticket' => $verifyTicket];
  1479. $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
  1480. $curl = new curl\Curl();
  1481. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1482. if (empty($result)) {
  1483. util::stop('没有取到ComponentAccessToken');
  1484. }
  1485. $result = Json::decode($result);
  1486. if (isset($result['component_access_token']) == false || empty($result['component_access_token'])) {
  1487. echo '<pre>';
  1488. print_r($result);
  1489. Yii::info('get component access token error:' . json_encode($result));
  1490. Yii::$app->end();
  1491. }
  1492. $component_access_token = $result['component_access_token'];
  1493. $expiresIn = $result['expires_in'];
  1494. $oData = [];
  1495. $oData['componentAccessToken'] = $component_access_token;
  1496. $oData['componentAccessTokenTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短
  1497. xhWxOpenService::updateById($id, $oData);
  1498. return $component_access_token;
  1499. } else {
  1500. return $componentAccessToken;
  1501. }
  1502. }
  1503. /**
  1504. * 微信开放平台获取预授权码pre_auth_code
  1505. */
  1506. public static function getPreAuthCode($open)
  1507. {
  1508. $id = $open['id'];
  1509. $preAuthCode = $open['preAuthCode'];
  1510. $preAuthCodeTime = $open['preAuthCodeTime'];
  1511. $now = time();
  1512. if ($now > strtotime($preAuthCodeTime)) {
  1513. $token = self::getComponentAccessToken($open);
  1514. $appId = $open['appId'];
  1515. $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
  1516. $curl = new curl\Curl();
  1517. $data = ['component_appid' => $appId];
  1518. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1519. $result = Json::decode($result);
  1520. Yii::info($result);
  1521. if (isset($result['pre_auth_code']) == false || empty($result['pre_auth_code'])) {
  1522. echo "没有取到pre_auth_code,原因:" . json_encode($result) . " appid:" . $appId . " token:" . $token;
  1523. Yii::$app->end();
  1524. }
  1525. $preAuthCode = $result['pre_auth_code'];
  1526. $expiresIn = $result['expires_in'];
  1527. $oData = [];
  1528. $oData['preAuthCode'] = $preAuthCode;
  1529. $oData['preAuthCodeTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短100秒
  1530. xhWxOpenService::updateById($id, $oData);
  1531. return $preAuthCode;
  1532. } else {
  1533. return $preAuthCode;
  1534. }
  1535. }
  1536. /**
  1537. * 微信开放平台使用授权码换取公众号的接口调用凭据和授权信息
  1538. */
  1539. public static function getAuthorizer($code, $open)
  1540. {
  1541. $appId = $open['appId'];
  1542. $accessToken = self::getComponentAccessToken($open);
  1543. $url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$accessToken}";
  1544. $curl = new curl\Curl();
  1545. $data = ['authorization_code' => $code, 'component_appid' => $appId];
  1546. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1547. $result = Json::decode($result);
  1548. return $result;
  1549. }
  1550. //微信开放平台获取授权方的公众号帐号基本信息 ssh 2020.3.11
  1551. public static function getAuthorizerInfo($authorizeAppId, $open)
  1552. {
  1553. $appId = $open['appId'];
  1554. $accessToken = self::getComponentAccessToken($open);
  1555. $url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$accessToken}";
  1556. $curl = new curl\Curl();
  1557. $data = ['component_appid' => $appId, 'authorizer_appid' => $authorizeAppId];
  1558. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1559. $result = Json::decode($result);
  1560. return $result;
  1561. }
  1562. }