miniUtil.php 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965
  1. <?php
  2. namespace common\components;
  3. use bizHd\wx\services\WxBaseService;
  4. use bizHd\wx\services\WxMiniBaseService;
  5. use common\services\xhMerchantExtendService;
  6. use Yii;
  7. use yii\helpers\Json;
  8. use linslin\yii2\curl;
  9. use common\services\xhWxOpenService;
  10. use common\services\xhMerchantService;
  11. /**
  12. * 小程序开发文楼
  13. */
  14. class miniUtil
  15. {
  16. public $access_token;
  17. public function __construct($merchant = '', $ptStyle = 1)
  18. {
  19. $this->access_token = !empty($merchant) ? self::getMiniProgramAccessToken($merchant, $ptStyle) : '';
  20. }
  21. //获取用户基本信息
  22. public static function userInfo($openId, $merchant, $ptStyle = 0)
  23. {
  24. $accessToken = self::getAuthorizerAccessToken($merchant, $ptStyle);
  25. $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accessToken&openid=$openId";
  26. $curl = new curl\Curl();
  27. $result = $curl->get($url);
  28. $result = Json::decode($result);
  29. if (isset($result['errcode'])) {
  30. } else {
  31. return $result;
  32. }
  33. }
  34. //创建开放平台帐号
  35. public static function createOpenAccount($appId, $merchant, $ptStyle = 0)
  36. {
  37. $accessToken = self::getAuthorizerAccessToken($merchant, $ptStyle);
  38. $url = "https://api.weixin.qq.com/cgi-bin/open/create?access_token=" . $accessToken;
  39. $curl = new curl\Curl();
  40. $data = ['appid' => $appId];
  41. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  42. $result = Json::decode($result);
  43. return $result;
  44. }
  45. //绑定到开放平台
  46. public static function bindOpenAccount($appId, $openAppId, $merchant, $isMiniProgram, $ptStyle = 0)
  47. {
  48. if ($isMiniProgram) {
  49. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  50. } else {
  51. $accessToken = self::getAuthorizerAccessToken($merchant, $ptStyle);
  52. }
  53. $url = 'https://api.weixin.qq.com/cgi-bin/open/bind?access_token=' . $accessToken;
  54. $curl = new curl\Curl();
  55. $data = ['appid' => $appId, 'open_appid' => $openAppId];
  56. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  57. $result = Json::decode($result);
  58. return $result;
  59. }
  60. //获取公众号、小程序绑定的开放平台帐号
  61. public static function getOpenAccount($appId, $merchant, $isMiniProgram, $ptStyle = 0)
  62. {
  63. if ($isMiniProgram) {
  64. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  65. } else {
  66. $accessToken = self::getAuthorizerAccessToken($merchant, $ptStyle);
  67. }
  68. $url = "https://api.weixin.qq.com/cgi-bin/open/get?access_token=" . $accessToken;
  69. $curl = new curl\Curl();
  70. $data = ['appid' => $appId];
  71. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  72. $result = Json::decode($result);
  73. return $result;
  74. }
  75. //解绑公众号绑定的平台 ssh 2019.9.15
  76. public static function unbindAccount($merchant, $ptStyle = 0)
  77. {
  78. $accessToken = self::getAuthorizerAccessToken($merchant, $ptStyle);
  79. $url = "https://api.weixin.qq.com/cgi-bin/open/unbind?access_token=" . $accessToken;
  80. $curl = new curl\Curl();
  81. $openAppId = $merchant['openAppId'];
  82. $appId = $merchant['wxAppId'];
  83. $data = ['appid' => $appId, 'open_appid' => $openAppId];
  84. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  85. $result = Json::decode($result);
  86. return $result;
  87. }
  88. //解绑小程序绑定的平台 ssh 2019.9.15
  89. public static function unbindMiniProgram($merchant, $ptStyle = 0)
  90. {
  91. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  92. $url = "https://api.weixin.qq.com/cgi-bin/open/unbind?access_token=" . $accessToken;
  93. $curl = new curl\Curl();
  94. $openAppId = $merchant['openAppId'];
  95. $appId = $merchant['miniAppId'];
  96. $data = ['appid' => $appId, 'open_appid' => $openAppId];
  97. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  98. $result = Json::decode($result);
  99. return $result;
  100. }
  101. public static function getSubscribeUserList($merchant, $nextOpenId = '', $ptStyle = 1)
  102. {
  103. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  104. $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$accessToken&next_openid=$nextOpenId";
  105. $curl = new curl\Curl();
  106. $result = $curl->get($url);
  107. return Json::decode($result);
  108. }
  109. public static function batchGetUserInfo($merchant, $openIdList, $ptStyle)
  110. {
  111. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  112. $url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" . $accessToken;
  113. $format = [];
  114. foreach ($openIdList as $val) {
  115. $format[] = ['openid' => $val, 'lang' => "zh-CN"];
  116. }
  117. $newOpenIdList = ["user_list" => $format];
  118. $curl = new curl\Curl();
  119. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($newOpenIdList))->post($url);
  120. $result = Json::decode($result);
  121. return $result;
  122. }
  123. //查询所有分组
  124. public static function groupList($accessToken)
  125. {
  126. $url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=$accessToken";
  127. $curl = new curl\Curl();
  128. $result = $curl->get($url);
  129. $result = Json::decode($result);
  130. if (isset($result['errcode'])) {
  131. return null;
  132. } else {
  133. return $result;
  134. }
  135. }
  136. /**
  137. * 提交自定义菜单到微信平台
  138. */
  139. public function userMenuToWeiXin($menu)
  140. {
  141. $jsonData = urldecode(json_encode($menu, JSON_UNESCAPED_UNICODE));
  142. $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $this->access_token;
  143. $curl = new curl\Curl();
  144. $response = $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  145. return $response;
  146. }
  147. /**
  148. * 上传图片多媒体文件
  149. */
  150. public static function uploadImgMedia($merchant, $fullFile)
  151. {
  152. $access_token = self::getMiniProgramAccessToken($merchant, $ptStyle);
  153. $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $access_token . "&type=image";
  154. $curl = curl_init();
  155. if (class_exists('\CURLFile')) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
  156. $data = array('media' => new \CURLFile($fullFile));
  157. } else {
  158. $data = array('media' => file_get_contents($fullFile));
  159. }
  160. if (class_exists('\CURLFile')) {
  161. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
  162. } else {
  163. if (defined('CURLOPT_SAFE_UPLOAD')) {
  164. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
  165. }
  166. }
  167. curl_setopt($curl, CURLOPT_URL, $url);
  168. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  169. curl_setopt($curl, CURLOPT_POST, true);
  170. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  171. $result = curl_exec($curl);
  172. curl_close($curl);
  173. return json_decode($result);
  174. }
  175. /**
  176. * 上传视频文件
  177. * @param unknown_type
  178. * @param $merchant
  179. * @param $fullFile
  180. * @return mixed
  181. */
  182. public function uploadVideoMedia($merchant, $fullFile)
  183. {
  184. $access_token = self::getMiniProgramAccessToken($merchant, $ptStyle);
  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, $ptStyle)
  225. {
  226. $token = self::getMiniProgramAccessToken($merchant, $ptStyle);
  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, $ptStyle)
  238. {
  239. $token = self::getMiniProgramAccessToken($merchant, $ptStyle);
  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, $ptStyle)
  249. {
  250. $token = self::getMiniProgramAccessToken($merchant, $ptStyle);
  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, $ptStyle = 1)
  305. {
  306. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  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, $ptStyle = 1)
  320. {
  321. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  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, $ptStyle)
  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 ($ptStyle == 1) {
  340. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  341. }
  342. if ($ptStyle == 2) {
  343. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  344. }
  345. if ($ptStyle == 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, $ptStyle)
  361. {
  362. $appId = $merchant['wxAppId'];
  363. $open = [];
  364. if ($ptStyle == 1) {
  365. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  366. }
  367. if ($ptStyle == 2) {
  368. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  369. }
  370. if ($ptStyle == 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. return $data;
  398. }
  399. /**
  400. * 自动获取自己的信息(公众号的粉丝才能获取)
  401. */
  402. public static function autoGetUserInfo($openid, $merchant, $ptStyle)
  403. {
  404. $access_token = self::getMiniProgramAccessToken($merchant, $ptStyle);
  405. $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
  406. $curl = new curl\Curl();
  407. $result = $curl->get($url);
  408. $data = Json::decode($result);
  409. return $data;
  410. }
  411. /**
  412. * 网址接入验证
  413. */
  414. public static function signatureValidation()
  415. {
  416. $signature = $_GET['signature'];
  417. $timestamp = $_GET['timestamp'];
  418. $nonce = $_GET['nonce'];
  419. $account = $_GET['account'];
  420. $merchant = xhMerchantService::getByAccount($account);
  421. if ($merchant) {
  422. $token = $merchant['wxToken'];
  423. // 3个数值组成数组验证
  424. $tmpArr = array(
  425. $token,
  426. $timestamp,
  427. $nonce
  428. );
  429. // 字典排序
  430. sort($tmpArr, SORT_STRING);
  431. $tmpStr = implode($tmpArr);
  432. // sha1加密
  433. $tmpStr = sha1($tmpStr);
  434. if ($signature == $tmpStr) {
  435. return true;
  436. } else {
  437. return false;
  438. }
  439. } else {
  440. return false;
  441. }
  442. }
  443. //客服接口发消息
  444. public static function sendMsg($content, $merchant, $openId, $ptStyle)
  445. {
  446. $token = self::getMiniProgramAccessToken($merchant, $ptStyle);
  447. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}";
  448. $data = ['touser' => $openId, 'msgtype' => 'text', 'text' => ['content' => $content]];
  449. $curl = new curl\Curl();
  450. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  451. $result = Json::decode($result);
  452. return $result;
  453. }
  454. public static function sendImgMsg($mediaId, $merchant, $openId, $ptStyle)
  455. {
  456. $token = self::getMiniProgramAccessToken($merchant, $ptStyle);
  457. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}";
  458. $data = ['touser' => $openId, 'msgtype' => 'image', 'image' => ['media_id' => $mediaId]];
  459. $curl = new curl\Curl();
  460. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  461. $result = Json::decode($result);
  462. return $result;
  463. }
  464. public static function sendVideoMsg($mediaId, $merchant, $openId, $ptStyle)
  465. {
  466. $token = self::getMiniProgramAccessToken($merchant, $ptStyle);
  467. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}";
  468. $data = ['touser' => $openId, 'msgtype' => 'video', 'video' => ['media_id' => $mediaId,
  469. 'thumb_media_id' => $mediaId,
  470. 'title' => '因爱而生',
  471. 'description' => "情定原生,爱在今生;\n坐标:浙江,绍兴上虞;\n看到过一句话:“一个城市不过是几条巷道上,几间房子和几个人的组合。如果没有了这些,一个城市如同陨落,只剩下悲凉的记忆;”\n万事万物持续流变,珍爱的东西尤其不可能一直存在,如朝霞,如春花,如爱情;\n无论什么时候,不管天气好坏,都能拿出某些个让人喜欢的东西。",
  472. ]];
  473. $curl = new curl\Curl();
  474. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  475. $result = Json::decode($result);
  476. return $result;
  477. }
  478. /**
  479. * 消息模板,发送任务通知
  480. * @param unknown $data
  481. * @return mixed
  482. */
  483. public static function sendTaskInform($data, $merchant, $ptStyle)
  484. {
  485. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  486. $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}";
  487. $data = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  488. $curl = new curl\Curl();
  489. $response = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  490. $arr = json_decode($response);
  491. return $arr;
  492. }
  493. /**
  494. * 创建模板消息
  495. * @param unknown $accessToken
  496. * @param unknown $template_id_short
  497. * @return unknown
  498. */
  499. public static function tMessageCreate($merchant, $shortTemplateId, $ptStyle)
  500. {
  501. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  502. $url = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={$accessToken}";
  503. $post = array('template_id_short' => $shortTemplateId);
  504. $curl = new curl\Curl();
  505. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  506. $result = Json::decode($result);
  507. return $result;
  508. }
  509. /**
  510. * 删除模板消息
  511. */
  512. public static function delTMessage($merchant, $templateId, $ptStyle)
  513. {
  514. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  515. $url = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token={$accessToken}";
  516. $post = array('template_id' => $templateId);
  517. $curl = new curl\Curl();
  518. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  519. $result = Json::decode($result);
  520. return $result;
  521. }
  522. /**
  523. * 取所有模板消息
  524. */
  525. public function getAllTMessage($merchant, $ptStyle)
  526. {
  527. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  528. $url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={$accessToken}";
  529. $curl = new curl\Curl();
  530. $result = $curl->get($url);
  531. $result = Json::decode($result);
  532. return $result;
  533. }
  534. /**
  535. * 设置模板消息的行业
  536. */
  537. public function setTMIndustry($merchant, $industry_id1, $industry_id2, $ptStyle)
  538. {
  539. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  540. $url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={$accessToken}";
  541. $post = array('industry_id1' => $industry_id1, 'industry_id2' => $industry_id2);
  542. $curl = new curl\Curl();
  543. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  544. $result = Json::decode($result);
  545. return $result;
  546. }
  547. /**
  548. * 获取公众号的accessToken 公众号调用凭据
  549. */
  550. public static function getAuthorizerAccessToken($merchant, $ptStyle = 0)
  551. {
  552. $sjId = $merchant['id'];
  553. $open = [];
  554. if ($ptStyle == 1) {
  555. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  556. }
  557. if ($ptStyle == 2) {
  558. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  559. }
  560. if ($ptStyle == 3) {
  561. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  562. }
  563. if (empty($open)) {
  564. util::fail('没有找到平台');
  565. }
  566. $component_app_id = $open['appId'];
  567. $componentAccessToken = wxUtil::getComponentAccessToken($open);
  568. $appId = $merchant['wxAppId'];
  569. $wxAccessToken = $merchant['wxAccessToken'];
  570. $wxAccessTokenTime = $merchant['wxAccessTokenTime'];
  571. $authorize_refresh_token = $merchant['wxRefreshToken'];
  572. $now = time();
  573. if ($now > strtotime($wxAccessTokenTime)) {
  574. $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$componentAccessToken}";
  575. $data = ['component_appid' => $component_app_id, 'authorizer_appid' => $appId, 'authorizer_refresh_token' => $authorize_refresh_token];
  576. $curl = new curl\Curl();
  577. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  578. $result = Json::decode($result);
  579. if (isset($result['authorizer_access_token'])) {
  580. $authorize_access_token = $result['authorizer_access_token'];
  581. $expires_in = $result['expires_in'];
  582. $authorize_refresh_token = $result['authorizer_refresh_token'];
  583. $uData['wxRefreshToken'] = $authorize_refresh_token;;
  584. $uData['wxAccessToken'] = $authorize_access_token;
  585. $uData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  586. if ($ptStyle == 1) {
  587. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  588. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  589. if (!empty($wxBaseId)) {
  590. WxBaseService::updateById($wxBaseId, $uData);
  591. }
  592. } elseif ($ptStyle == 2) {
  593. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  594. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  595. if (!empty($wxBaseId)) {
  596. WxBaseService::updateById($wxBaseId, $uData);
  597. }
  598. } elseif ($ptStyle == 3) {
  599. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  600. $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
  601. if (!empty($wxBaseId)) {
  602. WxBaseService::updateById($wxBaseId, $uData);
  603. }
  604. } else {
  605. xhMerchantService::updateById($sjId, $uData);
  606. }
  607. return $authorize_access_token;
  608. }
  609. return;
  610. } else {
  611. return $wxAccessToken;
  612. }
  613. }
  614. /**
  615. * 获取小程序的accessToken
  616. */
  617. public static function getMiniProgramAccessToken($merchant, $ptStyle = 0)
  618. {
  619. $sjId = isset($merchant['id']) ? $merchant['id'] : 0;
  620. //$id = dict::getDict('openId');
  621. $open = [];
  622. if ($ptStyle == 1) {
  623. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  624. }
  625. if ($ptStyle == 2) {
  626. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  627. }
  628. if ($ptStyle == 3) {
  629. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  630. }
  631. if (empty($open)) {
  632. util::fail('没有找到平台信息');
  633. }
  634. $component_app_id = $open['appId'];
  635. $componentAccessToken = wxUtil::getComponentAccessToken($open);
  636. $appId = $merchant['miniAppId'];
  637. //$appId = $open['appId']; // TODO 要换回来
  638. if ($ptStyle == 1) {
  639. $miniAccessToken = $merchant['miniAccessToken'];
  640. $miniAccessTokenTime = $merchant['miniAccessTokenTime'];
  641. $miniRefreshToken = $merchant['miniRefreshToken'];
  642. } elseif ($ptStyle == 2) {
  643. $miniAccessToken = $merchant['miniAccessToken'];
  644. $miniAccessTokenTime = $merchant['miniAccessTokenTime'];
  645. $miniRefreshToken = $merchant['miniRefreshToken'];
  646. } elseif ($ptStyle == 3) {
  647. $miniAccessToken = $merchant['miniAccessToken'];
  648. $miniAccessTokenTime = $merchant['miniAccessTokenTime'];
  649. $miniRefreshToken = $merchant['miniRefreshToken'];
  650. } else {
  651. $extend = xhMerchantExtendService::getBySjId($sjId);
  652. $miniAccessToken = $extend['miniAccessToken'];
  653. $miniAccessTokenTime = $extend['miniAccessTokenTime'];
  654. $miniRefreshToken = $extend['miniRefreshToken'];
  655. }
  656. $now = time();
  657. if ($now > strtotime($miniAccessTokenTime)) {
  658. $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$componentAccessToken}";
  659. $data = ['component_appid' => $component_app_id, 'authorizer_appid' => $appId, 'authorizer_refresh_token' => $miniRefreshToken];
  660. $curl = new curl\Curl();
  661. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  662. $result = Json::decode($result);
  663. Yii::info('重新获取mini accesstoken:' . json_encode($result));
  664. if (isset($result['authorizer_access_token'])) {
  665. $expires_in = $result['expires_in'];
  666. $miniAccessToken = $result['authorizer_access_token'];
  667. $uData['miniRefreshToken'] = $result['authorizer_refresh_token'];
  668. $uData['miniAccessToken'] = $miniAccessToken;
  669. $uData['miniAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
  670. if ($ptStyle == 1) {
  671. //零售
  672. $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0;
  673. if (!empty($wxMiniBaseId)) {
  674. WxMiniBaseService::updateById($wxMiniBaseId, $uData);
  675. }
  676. } elseif ($ptStyle == 2) {
  677. //供货商
  678. $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0;
  679. if (!empty($wxMiniBaseId)) {
  680. WxMiniBaseService::updateById($wxMiniBaseId, $uData);
  681. }
  682. } elseif ($ptStyle == 3) {
  683. //商城
  684. $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0;
  685. if (!empty($wxMiniBaseId)) {
  686. WxMiniBaseService::updateById($wxMiniBaseId, $uData);
  687. }
  688. } else {
  689. //其它
  690. xhMerchantExtendService::updateBySjId($sjId, $uData);
  691. }
  692. return $miniAccessToken;
  693. }
  694. Yii::info('accessToken失效:sjId:' . $sjId);
  695. }
  696. return $miniAccessToken;
  697. }
  698. public static function saveWeixinImg($userId, $url, $class = 0)
  699. {
  700. $className = [
  701. '0' => 'weixinUserAvatar',//微信头像
  702. '1' => 'weixinUserImg',//微信公众号二维码
  703. '2' => 'weixinMpQrcode',
  704. '3' => 'weixinMpAvatar',
  705. ];
  706. $folder = Yii::getAlias('@webroot') . '/../../images';
  707. $pre = '/' . $className[$class] . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  708. if (!file_exists($folder . $pre))
  709. mkdir($folder . $pre, 0777, true);
  710. $randString = stringUtil::buildOrderNo();
  711. $name = md5($userId . $randString) . '.jpg';
  712. $fullFileName = $folder . $pre . $name;
  713. $fileName = $pre . $name;
  714. $curl = new curl\Curl();
  715. $result = $curl->get($url);
  716. $fp2 = @fopen($fullFileName, 'a');//文件大小
  717. fwrite($fp2, $result);
  718. fclose($fp2);
  719. return $fileName;
  720. }
  721. /**
  722. * 下载学员作品图片
  723. */
  724. public static function downloadStudentWorksImg($merchant, $mediaId, $savePathType = 'wxUserImg', $ptStyle = 1)
  725. {
  726. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  727. $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$mediaId}";
  728. $ch = curl_init($url);
  729. curl_setopt($ch, CURLOPT_HEADER, 0);
  730. curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出。
  731. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  732. $body = curl_exec($ch);
  733. $httpinfo = curl_getinfo($ch);
  734. curl_close($ch);
  735. preg_match('/\w\/(\w+)/i', $httpinfo["content_type"], $extmatches);//求出文件格式
  736. $fileExt = $extmatches[1];
  737. $imgSavePath = dict::getDict('imgSavePath');
  738. $comImgSavePath = $imgSavePath[$savePathType];
  739. $folder = Yii::getAlias('@webroot') . '/../../images';
  740. $pre = '/' . $comImgSavePath . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  741. if (!file_exists($folder . $pre)) {
  742. mkdir($folder . $pre, 0777, true);
  743. }
  744. $randString = stringUtil::buildOrderNo();
  745. $fullFileName = $folder . $pre . $randString . '.jpg';
  746. $fileName = $pre . $randString . '.jpg';
  747. $fp2 = @fopen($fullFileName, 'a');//文件大小
  748. fwrite($fp2, $body);
  749. fclose($fp2);
  750. $srcImg = $fullFileName;
  751. $dstImg300 = $folder . $pre . $randString . "_300.jpg";//生成300px缩略图,不保存到数据库
  752. util::img2thumb($srcImg, $dstImg300, $width = 300, 0, 0, 0);
  753. $dstImg100 = $folder . $pre . $randString . "_100.jpg";//生成50px缩略图,不保存到数据库
  754. util::img2thumb($srcImg, $dstImg100, $width = 100, 0, 0, 0);
  755. return $fileName;
  756. }
  757. /**
  758. * 获取media_id里的图片保存到服务器
  759. */
  760. public static function downloadmediaIdImg($merchant, $mediaId, $savePathType = 'wxUserImg', $ptStyle)
  761. {
  762. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  763. $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$mediaId}";
  764. $ch = curl_init($url);
  765. curl_setopt($ch, CURLOPT_HEADER, 0);
  766. curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出。
  767. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  768. $body = curl_exec($ch);
  769. $httpinfo = curl_getinfo($ch);
  770. curl_close($ch);
  771. preg_match('/\w\/(\w+)/i', $httpinfo["content_type"], $extmatches);//求出文件格式
  772. $fileExt = $extmatches[1];
  773. $imgSavePath = dict::getDict('imgSavePath');
  774. $comImgSavePath = $imgSavePath[$savePathType];
  775. $folder = Yii::getAlias('@webroot') . '/../../images';
  776. $pre = '/' . $comImgSavePath . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  777. if (!file_exists($folder . $pre)) {
  778. mkdir($folder . $pre, 0777, true);
  779. }
  780. $randString = stringUtil::buildOrderNo();
  781. $fullFileName = $folder . $pre . $randString . '.jpg';
  782. $fileName = $pre . $randString . '.jpg';
  783. $fp2 = @fopen($fullFileName, 'a');//文件大小
  784. fwrite($fp2, $body);
  785. fclose($fp2);
  786. $srcImg = $fullFileName;
  787. $mediumImg = $pre . $randString . "_200.jpg";
  788. $dstImg200 = $folder . $mediumImg;//生成200px缩略图,不保存到数据库
  789. util::img2thumb($srcImg, $dstImg200, $width = 200, 0, 0, 0);
  790. $smallImg = $pre . $randString . "_50.jpg";
  791. $dstImg50 = $folder . $smallImg;//生成50px缩略图,不保存到数据库
  792. util::img2thumb($srcImg, $dstImg50, $width = 50, 0, 0, 0);
  793. return ['large' => $fileName, 'medium' => $mediumImg, 'small' => $smallImg];
  794. }
  795. public static function createTag($merchant, $name, $ptStyle)
  796. {
  797. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  798. $url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token={$accessToken}";
  799. $post = ['tag' => ['name' => $name]];
  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 delTag($merchant, $id, $ptStyle)
  806. {
  807. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  808. $url = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={$accessToken}";
  809. $post = ['tag' => ['id' => $id]];
  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. public static function modTag($merchant, $id, $name, $ptStyle)
  816. {
  817. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  818. $url = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token={$accessToken}";
  819. $post = ['tag' => ['id' => $id, 'name' => $name]];
  820. $curl = new curl\Curl();
  821. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  822. $result = Json::decode($result);
  823. return $result;
  824. }
  825. /**
  826. * 获取商家所有标签
  827. */
  828. public static function getTag($merchant, $ptStyle)
  829. {
  830. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  831. $url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token={$accessToken}";
  832. $curl = new curl\Curl();
  833. $result = $curl->get($url);
  834. $result = Json::decode($result);
  835. return $result;
  836. }
  837. public function getUserTag($tagId, $nextOpenId = '')
  838. {
  839. $url = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=" . $this->access_token;
  840. $post = ['tagid' => $tagId, 'next_openid' => $nextOpenId];
  841. $curl = new curl\Curl();
  842. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  843. $result = Json::decode($result);
  844. return $result;
  845. }
  846. /**
  847. * 批量为用户打标签
  848. */
  849. public static function membersBatchTag($merchant, $openIdList, $tagId, $ptStyle)
  850. {
  851. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  852. $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={$accessToken}";
  853. $post = ['openid_list' => $openIdList, 'tagid' => $tagId];
  854. $curl = new curl\Curl();
  855. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  856. $result = Json::decode($result);
  857. return $result;
  858. }
  859. /**
  860. * 批量取消用户标签
  861. */
  862. public static function membersCancelTag($merchant, $openIdList, $tagId, $ptStyle)
  863. {
  864. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  865. $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={$accessToken}";
  866. $post = ['openid_list' => $openIdList, 'tagid' => $tagId];
  867. $curl = new curl\Curl();
  868. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url);
  869. $result = Json::decode($result);
  870. return $result;
  871. }
  872. /**
  873. * 新增临时素材
  874. */
  875. public static function uploadTempMedia($merchant, $fullPathImg, $ptStyle, $type = 'image')
  876. {
  877. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  878. $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$accessToken}&type=" . $type;
  879. $ch = curl_init();
  880. if (class_exists('CURLFile')) {// 这里用特性检测判断php版本
  881. curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
  882. $postData = array('media' => new \CURLFile(realpath($fullPathImg)));//>=5.5
  883. } else {
  884. if (defined('CURLOPT_SAFE_UPLOAD')) {
  885. curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
  886. $postData = array('media' => '@' . realpath($fullPathImg));//<=5.5
  887. }
  888. }
  889. curl_setopt($ch, CURLOPT_URL, $url);
  890. curl_setopt($ch, CURLOPT_POST, 1);
  891. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  892. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  893. $response = curl_exec($ch);
  894. $result = Json::decode($response);
  895. return $result;
  896. }
  897. /**
  898. * 获取临时素材
  899. */
  900. public static function getTempMaterial($merchant, $mediaId, $ptStyle)
  901. {
  902. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  903. $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id=" . $mediaId;
  904. $fileInfo = self::getTempMaterialInfo($url);
  905. if (empty($fileInfo) || isset($fileInfo['errcode'])) {
  906. $msg = '未错误哦~';
  907. return ['code' => 'A0002', 'msg' => $msg];
  908. }
  909. $fileName = substr(md5($mediaId), -4) . stringUtil::buildOrderNo() . '.amr';
  910. $preFolder = Yii::getAlias('@webroot') . '/../../images';
  911. $folder = '/weixinChatVoice/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  912. if (!file_exists($preFolder . $folder))
  913. mkdir($preFolder . $folder, 0777, true);
  914. $saveFile = $preFolder . $folder . $fileName;
  915. if (file_exists($saveFile) == false) {
  916. self::readTempMaterial($saveFile, $fileInfo["body"]);
  917. }
  918. return ['code' => 'A0001', 'msg' => 'success', 'data' => ['url' => $folder . $fileName]];
  919. }
  920. /**
  921. * 获取临时素材的头信息等
  922. */
  923. public static function getTempMaterialInfo($url)
  924. {
  925. $ch = curl_init($url);
  926. curl_setopt($ch, CURLOPT_HEADER, 0);
  927. curl_setopt($ch, CURLOPT_NOBODY, 0);//只取body头
  928. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  929. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  930. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  931. $package = curl_exec($ch);
  932. $httpinfo = curl_getinfo($ch);
  933. curl_close($ch);
  934. $imageAll = ['header' => $httpinfo, 'body' => $package];
  935. return $imageAll;
  936. }
  937. /**
  938. * 读取临时素材的资源
  939. */
  940. function readTempMaterial($filename, $fileContent)
  941. {
  942. $localFile = fopen($filename, 'w');
  943. if (false !== $localFile) {
  944. if (false !== fwrite($localFile, $fileContent)) {
  945. fclose($localFile);
  946. }
  947. }
  948. }
  949. /**
  950. * 创建门店
  951. */
  952. public function createStore($info)
  953. {
  954. $jsonData = urldecode(json_encode($info, JSON_UNESCAPED_UNICODE));
  955. $url = "http://api.weixin.qq.com/cgi-bin/poi/addpoi?access_token=" . $this->access_token;
  956. $curl = new curl\Curl();
  957. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  958. }
  959. /**
  960. * 查询门店信息
  961. */
  962. public function getStoreInfo($poi_id)
  963. {
  964. $data = ['poi_id' => $poi_id];
  965. $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  966. $url = "http://api.weixin.qq.com/cgi-bin/poi/getpoi?access_token=" . $this->access_token;
  967. $curl = new curl\Curl();
  968. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  969. }
  970. /**
  971. * 查询门店列表
  972. */
  973. public function getStoreList($begin = 0, $count = 20)
  974. {
  975. $data = ["begin" => $begin, "limit" => $count];
  976. $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  977. $url = "http://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" . $this->access_token;
  978. $curl = new curl\Curl();
  979. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  980. }
  981. /**
  982. * 查询门店列表 -- 重复 可删除
  983. */
  984. function getShopList($data)
  985. {
  986. $url = "https://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" . $this->access_token;
  987. $curl = new curl\Curl();
  988. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  989. $result = Json::decode($result);
  990. return $result;
  991. }
  992. /**
  993. * 修改门店服务信息
  994. */
  995. public function updateStore(array $buffer)
  996. {
  997. $jsonData = urldecode(json_encode($buffer, JSON_UNESCAPED_UNICODE));
  998. $url = "http://api.weixin.qq.com/cgi-bin/poi/updatepoi?access_token=" . $this->access_token;
  999. $curl = new curl\Curl();
  1000. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  1001. }
  1002. /**
  1003. * 删除门店
  1004. * @param $poi_id
  1005. * @return mixed
  1006. */
  1007. public function delStore($poi_id)
  1008. {
  1009. $data = ['poi_id' => $poi_id];
  1010. $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
  1011. $url = "http://api.weixin.qq.com/cgi-bin/poi/delpoi?access_token=" . $this->access_token;
  1012. $curl = new curl\Curl();
  1013. return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url);
  1014. }
  1015. /**
  1016. * 门店类目表
  1017. */
  1018. public function storeTypeList()
  1019. {
  1020. $url = "http://api.weixin.qq.com/cgi-bin/poi/getwxcategory?access_token=" . $this->access_token;
  1021. $curl = new curl\Curl();
  1022. return $curl->get($url);
  1023. }
  1024. /******************************* wifi *************************************/
  1025. /**
  1026. * 获取wifi门店列表
  1027. */
  1028. function getShopWifiList($pageindex = 1, $pagesize = 10)
  1029. {
  1030. $data = ["pageindex" => $pageindex, "pagesize" => $pagesize];
  1031. $url = "https://api.weixin.qq.com/bizwifi/shop/list?access_token=" . $this->access_token;
  1032. $curl = new curl\Curl();
  1033. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1034. $result = Json::decode($result);
  1035. return $result;
  1036. }
  1037. /**
  1038. * 添加密码型设备
  1039. * @param $shopId 门店ID
  1040. * @param $ssid 无线网络设备的ssid
  1041. * @param $pwd 无线网络设备的密码
  1042. * @return mixed
  1043. */
  1044. function addPasswordDevice($shopId, $ssid, $pwd)
  1045. {
  1046. $data = ["shop_id" => $shopId, "ssid" => $ssid, "password" => $pwd];
  1047. $url = "https://api.weixin.qq.com/bizwifi/device/add?access_token=" . $this->access_token;
  1048. $curl = new curl\Curl();
  1049. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1050. $result = Json::decode($result);
  1051. return $result;
  1052. }
  1053. /**
  1054. * 修改门店Wi-Fi(修改门店网络信息)
  1055. * @param $shopId
  1056. * @param $oldSsid
  1057. * @param $ssid
  1058. * @param string $pwd
  1059. * @return mixed
  1060. */
  1061. function updateDevice($shopId, $oldSsid, $ssid, $pwd = '')
  1062. {
  1063. $data = ["shop_id" => $shopId, "old_ssid" => $oldSsid, "ssid" => $ssid];
  1064. if (!empty($pwd)) {
  1065. $data["password"] = $pwd;
  1066. }
  1067. $url = "https://api.weixin.qq.com/bizwifi/shop/update?access_token=" . $this->access_token;
  1068. $curl = new curl\Curl();
  1069. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1070. $result = Json::decode($result);
  1071. return $result;
  1072. }
  1073. /**
  1074. * 删除密码型设备
  1075. * @param $bssid 无线网络设备无线mac地址
  1076. * @return mixed
  1077. */
  1078. function delPasswordDevice($bssid)
  1079. {
  1080. $data = ["bssid" => $bssid];
  1081. $url = "https://api.weixin.qq.com/bizwifi/device/delete?access_token=" . $this->access_token;
  1082. $curl = new curl\Curl();
  1083. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1084. $result = Json::decode($result);
  1085. return $result;
  1086. }
  1087. /**
  1088. * 查询门店Wi-Fi信息
  1089. * @param $shopId 门店ID
  1090. * @return mixed
  1091. */
  1092. function getShopWifi($shopId)
  1093. {
  1094. $data = ["shop_id" => $shopId];
  1095. $url = "https://api.weixin.qq.com/bizwifi/shop/get?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. return $result;
  1100. }
  1101. /**
  1102. * 获取物料二维码
  1103. * @param $shopId 门店ID
  1104. * @param $ssid 无线网络设备的ssid
  1105. * @param $img_id 物料样式编号(0-纯二维码,可用于自由设计宣传材料;1-二维码物料,155mm×215mm(宽×高),可直接张贴)
  1106. * @return mixed
  1107. */
  1108. function getWifiQrCode($shopId, $ssid, $img_id)
  1109. {
  1110. //$data = ["shop_id" => 429620, "ssid" => "WX567", "img_id" => $img_id];
  1111. $data = ["shop_id" => $shopId, "ssid" => $ssid, "img_id" => $img_id];
  1112. $url = "https://api.weixin.qq.com/bizwifi/qrcode/get?access_token=" . $this->access_token;
  1113. $curl = new curl\Curl();
  1114. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1115. $result = Json::decode($result);
  1116. return $result;
  1117. }
  1118. function getWifiUrl()
  1119. {
  1120. $url = "https://api.weixin.qq.com/bizwifi/account/get_connecturl?access_token=" . $this->access_token;
  1121. $curl = new curl\Curl();
  1122. $result = $curl->get($url);
  1123. $result = Json::decode($result);
  1124. return $result;
  1125. }
  1126. function generateShortUrl($longUrl)
  1127. {
  1128. $data = ["action" => "long2short", "long_url" => $longUrl,];
  1129. $url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" . $this->access_token;
  1130. $curl = new curl\Curl();
  1131. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1132. $result = Json::decode($result);
  1133. if (isset($result['errcode']) && $result['errcode'] == 0) {
  1134. return ['code' => 'A0001', 'data' => ['shortUrl' => $result['short_url']]];
  1135. }
  1136. return ['code' => 'A0002', 'data' => []];
  1137. }
  1138. //长链接转短链接 ssh 2019.9.26
  1139. public static function urlLongToShort($longUrl, $merchant)
  1140. {
  1141. $accessToken = self::getMiniProgramAccessToken($merchant);
  1142. $data = ["action" => "long2short", "long_url" => $longUrl,];
  1143. $url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" . $accessToken;
  1144. $curl = new curl\Curl();
  1145. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1146. $result = Json::decode($result);
  1147. $url = '';
  1148. if (isset($result['errcode']) && $result['errcode'] == 0) {
  1149. $url = $result['short_url'];
  1150. }
  1151. return ['url' => $url];
  1152. }
  1153. /**
  1154. * 拉取门店所有的设备信息
  1155. * @return array
  1156. */
  1157. public function getShopWifiListAll()
  1158. {
  1159. $startPage = 1;
  1160. $list = [];
  1161. while (true) {
  1162. $reList = $this->getShopWifiList($startPage, 20);
  1163. if ($startPage <= $reList['data']['pagecount']) {
  1164. $list = array_merge($list, $reList['data']['records']);
  1165. ++$startPage;
  1166. } else {
  1167. break;
  1168. }
  1169. }
  1170. return $list;
  1171. }
  1172. /**
  1173. * 通过 poi_id 从Wi-Fi门店列表中 获取 shopId
  1174. * @param $poiId
  1175. * @return bool
  1176. */
  1177. public function getShopId($poiId, $list = [])
  1178. {
  1179. if (empty($list)) {
  1180. $list = $this->getShopWifiListAll();
  1181. }
  1182. foreach ($list as $shop) {
  1183. if ($shop['poi_id'] == $poiId)
  1184. return (string)$shop['shop_id'];
  1185. }
  1186. return false;
  1187. }
  1188. //设置小程序服务器域名
  1189. public static function setDomain($merchant, $ptStyle = 0)
  1190. {
  1191. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1192. $url = "https://api.weixin.qq.com/wxa/modify_domain?access_token=" . $accessToken;
  1193. $curl = new curl\Curl();
  1194. $mallHost = Yii::$app->params['mallHost'];
  1195. if ($ptStyle == 1) {
  1196. $mallHost = Yii::$app->params['hdHost'];
  1197. }
  1198. $has = strpos($mallHost, 'https');
  1199. //如果不是https则换成https
  1200. if ($has === false) {
  1201. $mallHost = str_replace('http', 'https', $mallHost);
  1202. }
  1203. $data = [
  1204. "action" => "set",
  1205. "requestdomain" => [$mallHost],
  1206. "wsrequestdomain" => [$mallHost],
  1207. "uploaddomain" => [$mallHost],
  1208. "downloaddomain" => [$mallHost],
  1209. ];
  1210. print_r($data);
  1211. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1212. $respond = Json::decode($result);
  1213. print_r($respond);
  1214. }
  1215. //设置业务域名
  1216. public static function setWebViewDomain($merchant, $ptStyle = 0)
  1217. {
  1218. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1219. $url = "https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=" . $accessToken;
  1220. $curl = new curl\Curl();
  1221. $mallHost = Yii::$app->params['mallHost'];
  1222. if ($ptStyle == 1) {
  1223. $mallHost = Yii::$app->params['hdHost'];
  1224. }
  1225. $has = strpos($mallHost, 'https');
  1226. //如果不是https则换成https
  1227. if ($has === false) {
  1228. $mallHost = str_replace('http', 'https', $mallHost);
  1229. }
  1230. $data = [
  1231. "action" => "set",
  1232. "webviewdomain" => [$mallHost],
  1233. ];
  1234. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1235. $respond = Json::decode($result);
  1236. print_r($respond);
  1237. }
  1238. //为授权的小程序帐号上传小程序代码
  1239. public static function miniCommit($merchant, $templateId, $ptStyle = 0)
  1240. {
  1241. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1242. $url = 'https://api.weixin.qq.com/wxa/commit?access_token=' . $accessToken;
  1243. $curl = new curl\Curl();
  1244. $apiUrl = Yii::$app->params['mallHost'];
  1245. if ($ptStyle == 1) {
  1246. $apiUrl = Yii::$app->params['hdHost'];
  1247. }
  1248. $imgUrl = imgUtil::getPrefix();
  1249. //如果不是https则换成https
  1250. $has = strpos($apiUrl, 'https');
  1251. if ($has === false) {
  1252. $apiUrl = str_replace('http', 'https', $apiUrl);
  1253. }
  1254. //如果不是https则换成https
  1255. $has = strpos($imgUrl, 'https');
  1256. if ($has === false) {
  1257. $imgUrl = str_replace('http', 'https', $imgUrl);
  1258. }
  1259. $account = isset($merchant['id']) ? $merchant['id'] : 0;
  1260. $name = isset($merchant['name']) ? $merchant['name'] : '';
  1261. $open = [];
  1262. if ($ptStyle == 1) {
  1263. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  1264. }
  1265. if ($ptStyle == 2) {
  1266. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  1267. }
  1268. if ($ptStyle == 3) {
  1269. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  1270. }
  1271. if (empty($open)) {
  1272. util::fail('没有找到平台');
  1273. }
  1274. $name = isset($open['name']) ? $open['name'] : '';
  1275. $ext = [
  1276. 'extAppid' => $merchant['miniAppId'],
  1277. 'ext' => [
  1278. 'account' => $account,
  1279. 'apiHost' => $apiUrl,
  1280. 'socketApiHost' => str_replace("https://", "", $apiUrl),
  1281. 'imgHost' => $imgUrl,
  1282. 'name' => $name,
  1283. ],
  1284. ];
  1285. echo '<pre>';
  1286. print_r($ext);
  1287. Yii::info("ext:" . json_encode($ext));
  1288. $extJson = json_encode($ext);
  1289. $data = [
  1290. "template_id" => $templateId,
  1291. "ext_json" => $extJson,
  1292. "user_version" => date("mdHis"),
  1293. "user_desc" => date("mdHis")
  1294. ];
  1295. print_r($data);
  1296. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1297. $respond = Json::decode($result);
  1298. print_r($respond);
  1299. }
  1300. //获取体验小程序的体验二维码
  1301. public static function getExperienceQrCode($merchant, $page, $ptStyle = 0)
  1302. {
  1303. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1304. $path = urlencode($page);
  1305. $url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token={$accessToken}&path=" . $path;
  1306. $curl = new curl\Curl();
  1307. $result = $curl->get($url);
  1308. $file = dirUtil::getImgDir() . 'retail/miniExperience/' . $merchant['id'] . '.jpg';
  1309. file_put_contents($file, $result);
  1310. echo "<b /><img src='" . imgUtil::getPrefix() . "/retail/miniExperience/" . $merchant['id'] . ".jpg' />";
  1311. }
  1312. //获取授权小程序帐号已设置的类目
  1313. public static function getMiniCategory($merchant, $ptStyle = 0)
  1314. {
  1315. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1316. $url = "https://api.weixin.qq.com/wxa/get_category?access_token=" . $accessToken;
  1317. $curl = new curl\Curl();
  1318. $result = $curl->get($url);
  1319. $respond = Json::decode($result);
  1320. echo "<pre>";
  1321. print_r($respond);
  1322. }
  1323. //小程序支付成功后获取唯一ID ssh 2020.5.12
  1324. public static function getPaidUnionId($merchant, $miniOpenId, $mcId, $orderId, $ptStyle = 0)
  1325. {
  1326. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1327. $url = "https://api.weixin.qq.com/wxa/getpaidunionid?access_token={$accessToken}&openid={$miniOpenId}&mch_id={$mcId}&out_trade_no=" . (string)$orderId;
  1328. $curl = new curl\Curl();
  1329. $result = $curl->get($url);
  1330. $respond = Json::decode($result);
  1331. $unionId = isset($respond['unionid']) && !empty($respond['unionid']) ? $respond['unionid'] : '';
  1332. return $unionId;
  1333. }
  1334. //小程序加急审核 ssh 2020.4.20
  1335. public static function speedupAudit($merchant, $id, $ptStyle = 0)
  1336. {
  1337. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  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, $ptStyle = 0)
  1349. {
  1350. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  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, $ptStyle = 0)
  1360. {
  1361. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1362. $url = "https://api.weixin.qq.com/wxa/submit_audit?access_token=" . $accessToken;
  1363. $curl = new curl\Curl();
  1364. if ($ptStyle == 1) {
  1365. $data = [
  1366. "item_list" => [
  1367. [
  1368. "address" => $page,
  1369. "tag" => "花卉宝 花店",
  1370. "first_class" => "IT科技",
  1371. "second_class" => "软件服务提供商",
  1372. "first_id" => 210,
  1373. "second_id" => 413,
  1374. "title" => "花卉宝",
  1375. ],
  1376. ],
  1377. "feedback_info" => "",
  1378. "feedback_stuff" => "",
  1379. ];
  1380. } else {
  1381. $data = [
  1382. "item_list" => [
  1383. [
  1384. "address" => $page,
  1385. "tag" => "鲜花 花店",
  1386. "first_class" => "商家自营",
  1387. "second_class" => "鲜花/园艺/工艺品",
  1388. "first_id" => 304,
  1389. "second_id" => 323,
  1390. "title" => "商城",
  1391. ],
  1392. ],
  1393. "feedback_info" => "",
  1394. "feedback_stuff" => "",
  1395. ];
  1396. }
  1397. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1398. $respond = Json::decode($result);
  1399. echo "<pre>";
  1400. print_r($respond);
  1401. }
  1402. //查询最新一次提交的审核状态
  1403. public static function miniGetLatestAuditStatus($merchant, $ptStyle = 0)
  1404. {
  1405. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1406. $url = "https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=" . $accessToken;
  1407. $curl = new curl\Curl();
  1408. $result = $curl->get($url);
  1409. $respond = Json::decode($result);
  1410. echo "<pre>";
  1411. print_r($respond);
  1412. }
  1413. //发布已通过审核的小程序
  1414. public static function miniRelease($merchant, $ptStyle = 0)
  1415. {
  1416. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1417. $url = "https://api.weixin.qq.com/wxa/release?access_token=" . $accessToken;
  1418. $curl = new curl\Curl();
  1419. $result = $curl->setOption(CURLOPT_POSTFIELDS, '{}')->post($url);
  1420. $respond = Json::decode($result);
  1421. return $respond;
  1422. }
  1423. //撤回审核
  1424. public static function rollbackCheck($merchant, $ptStyle = 0)
  1425. {
  1426. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1427. $url = "https://api.weixin.qq.com/wxa/undocodeaudit?access_token=" . $accessToken;
  1428. $curl = new curl\Curl();
  1429. $result = $curl->get($url);
  1430. $respond = Json::decode($result);
  1431. echo "<pre>";
  1432. print_r($respond);
  1433. }
  1434. //申请会员的小程序码
  1435. public static function generateMemberCode($merchant, $shopId, $ptStyle = 0)
  1436. {
  1437. $fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
  1438. $behind = 'retail/mimiMemberCode/';
  1439. $filePath = dirUtil::getImgDir() . $behind;
  1440. if (!file_exists($filePath)) {
  1441. mkdir($filePath, 0777, true);
  1442. }
  1443. $file = $filePath . $fileName;
  1444. if (file_exists($file)) {
  1445. return $behind . $fileName;
  1446. }
  1447. $path = 'pages/home/user?scan=1&shopId=' . $shopId;
  1448. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1449. $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
  1450. $curl = new curl\Curl();
  1451. $data = [
  1452. "path" => $path,
  1453. "width" => 1000,
  1454. ];
  1455. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1456. file_put_contents($file, $result);
  1457. return $behind . $fileName;
  1458. }
  1459. public static function generateShortLink($merchant, $pageUrl, $pageTitle, $ptStyle)
  1460. {
  1461. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1462. $url = "https://api.weixin.qq.com/wxa/genwxashortlink?access_token={$accessToken}";
  1463. $curl = new curl\Curl();
  1464. $data = [
  1465. "page_url" => $pageUrl,
  1466. "page_title" => $pageTitle,
  1467. 'is_permanent' => false,
  1468. ];
  1469. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1470. $result = Json::decode($result);
  1471. return $result;
  1472. }
  1473. //小程序码生成,永久有效,数量暂无限制 ssh 2020.4.17
  1474. public static function generateUnlimitedMiniCode($merchant, $page, $scene = '', $ptStyle = 0)
  1475. {
  1476. $id = isset($merchant['id']) ? $merchant['id'] : 0;
  1477. $fileName = md5($page . '_' . $scene) . '.jpg';
  1478. $behind = 'retail/mimiCode/' . date("Ym") . '/' . date("d") . '/' . $id . '/';
  1479. $filePath = dirUtil::getImgDir() . $behind;
  1480. if (!file_exists($filePath)) {
  1481. mkdir($filePath, 0777, true);
  1482. }
  1483. $file = $filePath . $fileName;
  1484. if (file_exists($file)) {
  1485. return $behind . $fileName;
  1486. }
  1487. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1488. $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
  1489. $curl = new curl\Curl();
  1490. $data = [];
  1491. if (!empty($page)) {
  1492. $data["page"] = $page;
  1493. }
  1494. $data["scene"] = $scene;
  1495. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1496. Yii::info('获取小程序图片资源:' . json_encode($result));
  1497. file_put_contents($file, $result);
  1498. //上传oss
  1499. $obj = $behind . $fileName;
  1500. $obj = ltrim($obj, "/");
  1501. oss::uploadImage($obj, $file);
  1502. return $behind . $fileName;
  1503. }
  1504. //生成充值码,永久有效,数量暂无限制 ssh 20250307
  1505. public static function generateUnlimitedRechargeMiniCode($merchant, $page, $scene = '', $ptStyle = 0)
  1506. {
  1507. $id = isset($merchant['id']) ? $merchant['id'] : 0;
  1508. $fileName = md5($page . '_' . $scene) . '.jpg';
  1509. $behind = 'retail/rechargeCode/' . date("Ym") . '/' . date("d") . '/' . $id . '/';
  1510. $filePath = dirUtil::getImgDir() . $behind;
  1511. if (!file_exists($filePath)) {
  1512. mkdir($filePath, 0777, true);
  1513. }
  1514. $file = $filePath . $fileName;
  1515. if (file_exists($file)) {
  1516. return $behind . $fileName;
  1517. }
  1518. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1519. $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
  1520. $curl = new curl\Curl();
  1521. $data = [];
  1522. if (!empty($page)) {
  1523. $data["page"] = $page;
  1524. }
  1525. $data["scene"] = $scene;
  1526. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1527. Yii::info('获取小程序图片资源:' . json_encode($result));
  1528. file_put_contents($file, $result);
  1529. //上传oss
  1530. $obj = $behind . $fileName;
  1531. $obj = ltrim($obj, "/");
  1532. oss::uploadImage($obj, $file);
  1533. return $behind . $fileName;
  1534. }
  1535. //微信开放平台获取component_access_token
  1536. public static function getComponentAccessToken($open)
  1537. {
  1538. $id = $open['id'];
  1539. $componentAccessToken = $open['componentAccessToken'];
  1540. $componentAccessTokenTime = $open['componentAccessTokenTime'];
  1541. $now = time();
  1542. if ($now > strtotime($componentAccessTokenTime)) {
  1543. $appId = $open['appId'];
  1544. $appSecret = $open['appSecret'];
  1545. $verifyTicket = $open['verifyTicket'];
  1546. $data = ['component_appid' => $appId, 'component_appsecret' => $appSecret, 'component_verify_ticket' => $verifyTicket];
  1547. $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
  1548. $curl = new curl\Curl();
  1549. $curl->setOption(CURLOPT_SSL_VERIFYPEER, false);
  1550. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1551. if (empty($result)) {
  1552. util::stop('没有取到ComponentAccessToken');
  1553. }
  1554. $result = Json::decode($result);
  1555. if (isset($result['component_access_token']) == false || empty($result['component_access_token'])) {
  1556. Yii::info('get component access token error:' . json_encode($result));
  1557. Yii::$app->end();
  1558. }
  1559. $component_access_token = $result['component_access_token'];
  1560. $expiresIn = $result['expires_in'];
  1561. $oData = [];
  1562. $oData['componentAccessToken'] = $component_access_token;
  1563. $oData['componentAccessTokenTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短
  1564. xhWxOpenService::updateById($id, $oData);
  1565. return $component_access_token;
  1566. } else {
  1567. return $componentAccessToken;
  1568. }
  1569. }
  1570. /**
  1571. * 微信开放平台获取预授权码pre_auth_code
  1572. */
  1573. public static function getPreAuthCode($open)
  1574. {
  1575. $id = $open['id'];
  1576. $preAuthCode = $open['preAuthCode'];
  1577. $preAuthCodeTime = $open['preAuthCodeTime'];
  1578. $now = time();
  1579. if ($now > strtotime($preAuthCodeTime)) {
  1580. $token = self::getComponentAccessToken($open);
  1581. $appId = $open['appId'];
  1582. $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
  1583. $curl = new curl\Curl();
  1584. $data = ['component_appid' => $appId];
  1585. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1586. $result = Json::decode($result);
  1587. Yii::info($result);
  1588. if (isset($result['pre_auth_code']) == false || empty($result['pre_auth_code'])) {
  1589. echo "没有取到pre_auth_code,原因:" . json_encode($result) . " appid:" . $appId . " token:" . $token;
  1590. Yii::$app->end();
  1591. }
  1592. $preAuthCode = $result['pre_auth_code'];
  1593. $expiresIn = $result['expires_in'];
  1594. $oData = [];
  1595. $oData['preAuthCode'] = $preAuthCode;
  1596. $oData['preAuthCodeTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短100秒
  1597. xhWxOpenService::updateById($id, $oData);
  1598. return $preAuthCode;
  1599. } else {
  1600. return $preAuthCode;
  1601. }
  1602. }
  1603. /**
  1604. * 微信开放平台使用授权码换取公众号的接口调用凭据和授权信息
  1605. * authorizer_access_token authorizer_refresh_token
  1606. */
  1607. public static function getAuthorizer($code, $ptStyle)
  1608. {
  1609. $open = [];
  1610. if ($ptStyle == 1) {
  1611. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  1612. }
  1613. if ($ptStyle == 2) {
  1614. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]);
  1615. }
  1616. if ($ptStyle == 3) {
  1617. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]);
  1618. }
  1619. if (empty($open)) {
  1620. util::fail('没有找到平台');
  1621. }
  1622. $appId = $open['appId'];
  1623. $accessToken = self::getComponentAccessToken($open);
  1624. $url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$accessToken}";
  1625. $curl = new curl\Curl();
  1626. $data = ['authorization_code' => $code, 'component_appid' => $appId];
  1627. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1628. $result = Json::decode($result);
  1629. return $result;
  1630. }
  1631. //微信开放平台获取授权方的公众号帐号基本信息 ssh 2020.3.11
  1632. public static function getAuthorizerInfo($authorizeAppId, $open)
  1633. {
  1634. $appId = $open['appId'];
  1635. $accessToken = self::getComponentAccessToken($open);
  1636. $url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$accessToken}";
  1637. $curl = new curl\Curl();
  1638. $data = ['component_appid' => $appId, 'authorizer_appid' => $authorizeAppId];
  1639. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1640. $result = Json::decode($result);
  1641. return $result;
  1642. }
  1643. /**************************即时配送相关接口 START *****************************************/
  1644. //开通即时配送权限
  1645. public static function openLocalExpress($merchant, $ptStyle = 0)
  1646. {
  1647. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1648. $url = "https://api.weixin.qq.com/cgi-bin/express/local/business/open?access_token=" . $accessToken;
  1649. $curl = new curl\Curl();
  1650. $result = $curl->get($url);
  1651. $respond = Json::decode($result);
  1652. echo "<pre>";
  1653. print_r($respond);
  1654. }
  1655. //异常件退回商家商家确认收货接口
  1656. //场景:当订单配送异常,骑手把货物退还给商家,商家收货以后调用本接口返回确认收货
  1657. /*
  1658. * $data
  1659. * {
  1660. "shopid": "123456",
  1661. "shop_order_id": "123456",
  1662. "shop_no": "shop_no_111"
  1663. "waybill_id": "123456",
  1664. "remark": "remark",
  1665. "delivery_sign": "123456"
  1666. }
  1667. */
  1668. public static function abnormalConfirm($data, $merchant, $ptStyle = 0)
  1669. {
  1670. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1671. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/order/confirm_return?access_token=' . $accessToken;
  1672. $curl = new curl\Curl();
  1673. $data = Json::encode($data);
  1674. $result = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  1675. $respond = Json::decode($result);
  1676. return $respond;
  1677. }
  1678. //即时配送,拉取已绑定账号 ssh 2021.2.1
  1679. public static function getBindAccount($merchant, $ptStyle = 0)
  1680. {
  1681. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1682. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/shop/get?access_token=' . $accessToken;
  1683. $curl = new curl\Curl();
  1684. $result = $curl->setOption(CURLOPT_POSTFIELDS, '{}')->post($url);
  1685. $respond = Json::decode($result);
  1686. return $respond;
  1687. }
  1688. //获取已支持的配送公司列表接口 lqh 2021.2.2
  1689. public static function getAllImmeDelivery($merchant, $ptStyle = 0)
  1690. {
  1691. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1692. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/delivery/getall?access_token=' . $accessToken;
  1693. $curl = new curl\Curl();
  1694. $result = $curl->setOption(CURLOPT_POSTFIELDS, '{}')->post($url);
  1695. $respond = Json::decode($result);
  1696. return $respond;
  1697. }
  1698. //下配送单接口 lqh 2021.2.2
  1699. //场景:
  1700. /*
  1701. * 商家可调用本接口向配送公司请求下配送单,配送公司会返回这一单的配送单号、配送费、预计骑手接单时间等信息。
  1702. 如遇下单错误,请先确认一下编码方式,python建议 json.dumps(b, ensure_ascii=False),php建议 json_encode($arr, JSON_UNESCAPED_UNICODE) 可预约时间:达达:72小时内,闪送2小时以后,48小时以内
  1703. {
  1704. "resultcode": 0,
  1705. "resultmsg": "ok",
  1706. "fee": 10, 实际运费(单位:元),运费减去优惠券费用
  1707. "deliverfee": 10, 运费(单位:元)
  1708. "couponfee": 0, 优惠券费用(单位:元)
  1709. "tips": 0, 小费(单位:元)
  1710. "insurancfee": 0, 保价费(单位:元)
  1711. "distance": 1000, 配送距离(整数单位:米)
  1712. "waybill_id": "123456789", 配送单号
  1713. "order_status": 101, 配送状态。
  1714. "finish_code": 1024, 收货码
  1715. "pickup_code": 2048, 取货码
  1716. "dispatch_duration": 300 预计骑手接单时间,单位秒,比如5分钟,就填300, 无法预计填0
  1717. }
  1718. */
  1719. public static function addOrder($data, $merchant, $ptStyle = 0)
  1720. {
  1721. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1722. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/order/add?access_token=' . $accessToken;
  1723. $curl = new curl\Curl();
  1724. $data = Json::encode($data);
  1725. $result = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  1726. $respond = Json::decode($result);
  1727. return $respond;
  1728. }
  1729. //可以对待接单状态的订单增加小费。需要注意:订单的小费,以最新一次加小费动作的金额为准,故下一次增加小费额必须大于上一次小费额
  1730. /*
  1731. * {
  1732. "shopid": "123456",
  1733. "shop_order_id": "123456",
  1734. "waybill_id": "123456",
  1735. "tips": 5,
  1736. "remark": "gogogo",
  1737. "delivery_sign": "123456",
  1738. "shop_no": "shop_no_111"
  1739. }
  1740. */
  1741. public static function addTip($data, $merchant, $ptStyle = 0)
  1742. {
  1743. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1744. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/order/addtips?access_token=' . $accessToken;
  1745. $curl = new curl\Curl();
  1746. $data = Json::encode($data);
  1747. $result = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  1748. $respond = Json::decode($result);
  1749. return $respond;
  1750. }
  1751. //取消配送单接口 lqh 2021.2.3
  1752. public static function cancelOrder($data, $merchant, $ptStyle = 0)
  1753. {
  1754. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1755. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/order/cancel?access_token=' . $accessToken;
  1756. $curl = new curl\Curl();
  1757. $data = Json::encode($data);
  1758. $result = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  1759. $respond = Json::decode($result);
  1760. return $respond;
  1761. }
  1762. //拉取配送单信息 lqh 2021.2.3
  1763. public static function getOrder($data, $merchant, $ptStyle = 0)
  1764. {
  1765. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1766. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/order/get?access_token=' . $accessToken;
  1767. $curl = new curl\Curl();
  1768. $data = Json::encode($data);
  1769. $result = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  1770. $respond = Json::decode($result);
  1771. return $respond;
  1772. }
  1773. //模拟配送公司更新配送单状态, 该接口只用于沙盒环境,即订单并没有真实流转到运力方
  1774. public static function mockUpdateOrder($data, $merchant, $ptStyle = 0)
  1775. {
  1776. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1777. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/test_update_order?access_token=' . $accessToken;
  1778. $curl = new curl\Curl();
  1779. $data = Json::encode($data);
  1780. $result = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  1781. $respond = Json::decode($result);
  1782. return $respond;
  1783. }
  1784. //预下配送单接口
  1785. //在用户提交外卖订单时,商家可调用本接口查询配送公司是否可接单、预计多久接单、运费预估等。
  1786. //预估运费可作为展示给用户的运费参考值。
  1787. public static function preAddOrder($data, $merchant, $ptStyle = 0)
  1788. {
  1789. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1790. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/order/pre_add?access_token=' . $accessToken;
  1791. $curl = new curl\Curl();
  1792. $data = Json::encode($data);
  1793. $result = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  1794. $respond = Json::decode($result);
  1795. return $respond;
  1796. }
  1797. //预取消配送单接口
  1798. //在正式取消配送单前,商家可调用本接口查询该订单是否可以取消,取消订单配送公司需要扣除的费用是多少
  1799. public static function preCancelOrder($data, $merchant, $ptStyle = 0)
  1800. {
  1801. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1802. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/order/precancel?access_token=' . $accessToken;
  1803. $curl = new curl\Curl();
  1804. $data = Json::encode($data);
  1805. $result = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  1806. $respond = Json::decode($result);
  1807. return $respond;
  1808. }
  1809. //重新下单
  1810. //在调用下配送单接口、订单被取消、过期或者投递异常的情况下,可调用此接口,重新下单,需要保持orderid一致。
  1811. //备注:美团不支持重新下单接口,如果订单被取消商家需要重新下单,请修改orderid之后,调用下配送单接口下单。
  1812. public static function reOrder($data, $merchant, $ptStyle = 0)
  1813. {
  1814. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1815. $url = 'https://api.weixin.qq.com/cgi-bin/express/local/business/order/readd?access_token=' . $accessToken;
  1816. $curl = new curl\Curl();
  1817. $data = Json::encode($data);
  1818. $result = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
  1819. $respond = Json::decode($result);
  1820. return $respond;
  1821. }
  1822. /**************************即时配送相关接口 END *****************************************/
  1823. //发送订阅消息通知 ssh 2023511
  1824. public static function commonSendSubscribeMessage($merchant, $ptStyle, $msgId, $miniOpenId, $page, $msg)
  1825. {
  1826. $accessToken = self::getMiniProgramAccessToken($merchant, $ptStyle);
  1827. $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $accessToken;
  1828. $curl = new curl\Curl();
  1829. $data = ['template_id' => $msgId, 'page' => $page, 'touser' => $miniOpenId, 'data' => $msg];
  1830. $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
  1831. Yii::info('订阅消息通知返回:' . $result);
  1832. $result = Json::decode($result);
  1833. return $result;
  1834. }
  1835. }