CustomMsgService.php 133 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909
  1. <?php
  2. /**
  3. * Created by sublime.
  4. * User: wosinC
  5. * Date: 2017/12/2
  6. * Time: 上午11:39
  7. */
  8. namespace App\Modules\OfficialAccount\Services;
  9. use App\Modules\Book\Models\DataAnalysisBookConfig;
  10. use App\Modules\OfficialAccount\Services\ForceSubscribeService;
  11. use App\Modules\OfficialAccount\Services\TemplateCustomSendService;
  12. use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
  13. use App\Modules\OfficialAccount\Models\OfficialAccount;
  14. use App\Modules\OfficialAccount\Models\OfficialCustomMsg;
  15. use App\Modules\OfficialAccount\Models\CustomMsgSwitchs;
  16. use App\Modules\OfficialAccount\Models\CustomMsgSwitchsMsgs;
  17. use App\Modules\OfficialAccount\Models\CustomSendMsgs;
  18. use App\Modules\OfficialAccount\Models\DistributionChannelSetting;
  19. use App\Modules\OfficialAccount\Models\OfficialImgtextUrls;
  20. use App\Modules\User\Services\ReadRecordService;
  21. use App\Modules\User\Services\UserService;
  22. use App\Modules\Book\Services\BookConfigService;
  23. use App\Modules\OfficialAccount\Services\OfficialAccountService;
  24. use App\Modules\OfficialAccount\Services\SmartPushMsgService;
  25. use App\Modules\Statistic\Services\DataAnalysisChapterService;
  26. use App\Modules\Promotion\Services\PromotionService;
  27. use App\Modules\Channel\Services\ChannelService;
  28. use App\Modules\OfficialAccount\Models\MediaCustomer;
  29. use App\Modules\OfficialAccount\Models\CustomPushActivitys;
  30. use App\Modules\OfficialAccount\Models\CustomPushConfigs;
  31. use App\Modules\OfficialAccount\Models\CustomPushConfigContents;
  32. use App\Modules\OfficialAccount\Models\CustomSendDayStats;
  33. use App\Modules\Book\Models\Chapter;
  34. use App\Modules\WechatMaterial\Services\BatchWechatCustomSendService;
  35. use GuzzleHttp\Client;
  36. use GuzzleHttp\Pool;
  37. use GuzzleHttp\Promise;
  38. use App\Libs\OSS;
  39. use GuzzleHttp\Psr7\Request;
  40. use Redis;
  41. use App\Jobs\SendNews;
  42. use App\Jobs\SendSmartNews;
  43. use App\Jobs\SendTexts;
  44. use App\Jobs\SendTemplate;
  45. use App\Jobs\CustomMsgSendJob;
  46. use DB;
  47. use Hashids;
  48. class CustomMsgService
  49. {
  50. /**
  51. * 通过channelName和text获取神书
  52. */
  53. static function customerMsgByChannelAndText($channelname, $text)
  54. {
  55. return OfficialCustomMsg::customerMsgByChannelAndText($channelname, $text);
  56. }
  57. /**
  58. * 通过分销渠道ID获取客服图片
  59. */
  60. static function customerImgUrlByChannelId($distribution_channel_id)
  61. {
  62. return DistributionChannelSetting::customerImgUrlByChannelId($distribution_channel_id);
  63. }
  64. /**
  65. * 添加客服图片
  66. */
  67. static function updateCustomerImgUrl($customerImgPram)
  68. {
  69. //通过分销渠道号寻找客服图片
  70. $customerImgs = DistributionChannelSetting::customerImgUrlByChannelId($customerImgPram['distribution_channel_id']);
  71. if (empty($customerImgs)) {
  72. //2,删除media_customer表中老的客服图片的mediaid,
  73. //以便灵杰公众号交互下次该渠道请求客服图片时重新去渠道获取新的客服图片
  74. MediaCustomer::where('distribution_channel_id', $customerImgPram['distribution_channel_id'])->delete();
  75. //该渠道配置表中增加客服图片
  76. return DistributionChannelSetting::create($customerImgPram);
  77. } else {
  78. //1,该渠道配置表中更新客服图片
  79. $customerImgs['customer_img_url'] = $customerImgPram['customer_img_url'];
  80. $customerImgs->save();
  81. //2,删除media_customer表中老的客服图片的mediaid,
  82. //以便灵杰公众号交互下次该渠道请求客服图片时重新去渠道获取新的客服图片
  83. MediaCustomer::where('distribution_channel_id', $customerImgPram['distribution_channel_id'])->delete();
  84. return $customerImgs;
  85. }
  86. }
  87. /**
  88. * 未支付订单发送客服消息
  89. */
  90. static function sendUnpaid()
  91. {
  92. //1,遍历渠道表
  93. $distribution_channels = ChannelService::getAllChannels();
  94. $today = date('Y-m-d');
  95. for ($i = 0; $i < count($distribution_channels); $i++) {
  96. //2,判断该渠道下有没有开启未支付订单的智能推送
  97. $distribution_channel_id = $distribution_channels[$i]['id'];
  98. // 针对订单级别,一个用户可能扔多次
  99. $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:' . $distribution_channel_id;
  100. $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id, 'not_pay');
  101. if (!empty($customMsgSwitch)) {
  102. if ($customMsgSwitch['status'] == '1') {
  103. \Log::info('<----获取 开启订单未支付提醒的 渠道号---->');
  104. \Log::info($distribution_channel_id);
  105. //3,如果开启了 先获取该渠道下redis待发送的用户
  106. $not_order_users = Redis::hgetall($key);
  107. //\Log::info('<----获取 渠道下 用户---->');
  108. if (!empty($not_order_users)) {
  109. $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id, 'not_pay', date("Y-m-d"));
  110. if (empty($customSendStatsCount)) {
  111. $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
  112. $customSendDayStats['from'] = 'not_pay';
  113. $customSendDayStats['push_user_num'] = count($not_order_users);
  114. $customSendDayStats['date'] = date("Y-m-d");
  115. CustomSendDayStats::create($customSendDayStats);
  116. } else {
  117. $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num'] + count($not_order_users);
  118. $customSendStatsCount->save();
  119. }
  120. foreach ($not_order_users as $uid => $time) {
  121. //\Log::info('<----redis中找到用户 获取uid 时间差---->');
  122. //\Log::info($uid);
  123. //\Log::info(time()-$time);
  124. //4,计算这些用户未支付订单是否大于1小时
  125. $now_time = time() - $time;
  126. if ($now_time > 3600) {
  127. //5,从Redis中获取并判断这些用户 今日是否已经发送过“未支付订单提醒”
  128. $today_key = "sended_not_pay_uid:distribution_channel_id:" . $distribution_channel_id . ":day:" . $today;
  129. if (!Redis::sismember($today_key, $uid)) {
  130. //6,判断用户当前是否为强关用户
  131. $force_users = ForceSubscribeService::allForceSubscribeUsersByUid(compact('uid'));
  132. if (!empty($force_users)) {
  133. foreach ($force_users as $force_user) {
  134. \Log::info('nopaid_remind:' . $force_user['openid']);
  135. //(1),发送(文字)未支付客服提醒至RebitMQ
  136. self::add_text_task($force_user);
  137. //(2), 今日的redis增加一条记录,每天只发一次
  138. Redis::sadd($today_key, $uid);
  139. Redis::expire($today_key, 3600 * 24 * 3);
  140. }
  141. }
  142. //7,将该用户在未支付订单待发送的Redis中移除
  143. Redis::hdel($key, $uid);
  144. } else {
  145. //8,如果发送过,直接将该用户从未支付订单待发送redis中移除
  146. Redis::hdel($key, $uid);
  147. }
  148. }
  149. }
  150. } else {
  151. \Log::info('<----redis中该渠道下没有找到用户---->');
  152. }
  153. } else {
  154. //智能推送未支付订单关闭状态
  155. //直接删除该渠道下未支付订单的redis键
  156. Redis::del($key);
  157. }
  158. } else {
  159. //智能推送还未创建(默认关闭)
  160. //直接删除该渠道下未支付订单的redis键
  161. Redis::del($key);
  162. }
  163. }
  164. }
  165. /**
  166. * RebitMQ发送24小时未支付订单提醒(文字)
  167. */
  168. static function add_text_task($force_user)
  169. {
  170. $uid = $force_user['uid'];
  171. $distribution_channel_id = $force_user['distribution_channel_id'];
  172. //通过uid获取该用户最近阅读记录的书籍
  173. $userBook = ReadRecordService::getFirstReadRecord($uid);
  174. \Log::info('<----获取用户 最近阅读记录---->');
  175. if (!empty($userBook)) {
  176. $data = array();
  177. $data['openid'] = $force_user['openid'];
  178. $data['appid'] = $force_user['appid'];
  179. //用户最近阅读链接
  180. $continueReadUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/continue?fromtype=not_pay';
  181. //拼接文案和用户最近阅读书籍的链接以及书籍名称
  182. $data['content'] = '亲,你上次看的书还在等着你呐~点击继续阅读' . "\n" . '<a href="' . $continueReadUrl . '"> >《' . $userBook['book_name'] . '》</a>' . "\n" . '首冲50元即可畅读100万字,年费VIP更可全年无限畅读。' . "\n" . '为方便下次阅读,请' . '<a href="https://help.leyuee.com/top.html">' . '置顶公众号' . '</a>';
  183. $data['type'] = 'one_task';// last_task,one_task
  184. $data['task_id'] = 1;
  185. $data['send_time'] = date("Y-m-d H:i:s");
  186. $send_data = array(
  187. 'send_time' => date("Y-m-d H:i:s"),
  188. 'data' => $data
  189. );
  190. //\Log::info($data['openid']);
  191. //\Log::info($data['appid']);
  192. //\Log::info($data['content']);
  193. $delay = 0;
  194. $job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list');
  195. dispatch($job);
  196. } else {
  197. \Log::info('<----抱歉 没有最近阅读记录---->');
  198. }
  199. }
  200. /**
  201. * RebitMQ发送24小时未支付订单提醒(图文)
  202. */
  203. static function add_news_task($force_user, $officialCustomMsg)
  204. {
  205. $data = array();
  206. $data['openid'] = $force_user['openid'];
  207. $data['appid'] = $force_user['appid'];
  208. $data['news_content'] = '[[{"title":"' . $officialCustomMsg['title'] . '"},{"description":"' . $officialCustomMsg['description'] . '"},{"url":"' . $officialCustomMsg['url'] . '"},{"image":"' . $officialCustomMsg['image'] . '"}]]';
  209. $data['type'] = 'one_task';// last_task,one_task
  210. $data['task_id'] = 3;
  211. $data['send_time'] = date("Y-m-d H:i:s");
  212. $send_data = array(
  213. 'send_time' => date("Y-m-d H:i:s"),
  214. 'data' => $data
  215. );
  216. $delay = 0;
  217. $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
  218. dispatch($job);
  219. }
  220. /**
  221. * 三天回本推送(定时任务 12小时推)
  222. */
  223. static function add_news_recovery_push_hot()
  224. {
  225. \Log::info('=======================三天回本推送客服消息');
  226. //1,遍历渠道表
  227. $distribution_channels = ChannelService::getAllChannels();
  228. for ($k = 0; $k < count($distribution_channels); $k++) {
  229. //2,判断该渠道下有没有开启 未支付订单的智能推送
  230. $distribution_channel_id = $distribution_channels[$k]['id'];
  231. $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id, 'recovery_push');
  232. if (!empty($customMsgSwitch)) {
  233. if ($customMsgSwitch['status'] == '1') {
  234. \Log::info('<----开启客服的 渠道号---->');
  235. \Log::info($distribution_channel_id);
  236. //3,开通智能推送的渠道获取 渠道下的强关用户
  237. $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;
  238. $forceSubscribeUsersPrams['timeset'] = 43200;
  239. $force_user = ForceSubscribeService::forceSubscribeNewUsersByTimeset($forceSubscribeUsersPrams);
  240. //\Log::info('<----渠道下强关用户数---->');
  241. //\Log::info(count($force_user));
  242. $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id, 'recovery_push', date("Y-m-d"));
  243. if (empty($customSendStatsCount)) {
  244. $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
  245. $customSendDayStats['from'] = 'recovery_push';
  246. $customSendDayStats['push_user_num'] = count($force_user);
  247. $customSendDayStats['date'] = date("Y-m-d");
  248. CustomSendDayStats::create($customSendDayStats);
  249. } else {
  250. $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num'] + count($force_user);
  251. $customSendStatsCount->save();
  252. }
  253. for ($i = 0; $i < count($force_user); $i++) {
  254. //(1)通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息
  255. //(2)如果有,获取插入的时间,
  256. // 如果时间在今天之内,那就不发送,
  257. // 如果不是,就发送,并往Redis中插入一条数据
  258. $uid = $force_user[$i]['uid'];
  259. if (!Redis::hget('add_news_recovery_push_hot' . $uid, 'time')) {
  260. $bid = $force_user[$i]['bid'];
  261. $booksArray = [];
  262. //4,获取男频女频的标签文案
  263. $manPromotion = PromotionService::getRandomHeadline(1, 5);
  264. $womanPromotion = PromotionService::getRandomHeadline(2, 5);
  265. //7,获取和用户强关进来的书相同类型的5本优质评分的书籍
  266. // $books = BookConfigService::getSimpleChannelBook($bid,5);
  267. $books = BookConfigService::getSimpleChannelBookLoop($bid, 5, $uid);
  268. $bookUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com';
  269. $promotionNum = 0;
  270. if ($books) {
  271. foreach ($books as $key => $value) {
  272. //8,将这四本书作为推送的2-5条信息,同样拼接书籍信息和标签文案
  273. $urlBook = $value->url = $bookUrl . $value->url . '&fromtype=recovery_push';
  274. $channelName = $value->channel_name;
  275. $cover = $value->cover;
  276. if ($channelName == '男频') {
  277. $book['title'] = $manPromotion[$promotionNum]['title'];
  278. $book['description'] = $manPromotion[$promotionNum]['title'];
  279. } else {
  280. $book['title'] = $womanPromotion[$promotionNum]['title'];
  281. $book['description'] = $womanPromotion[$promotionNum]['title'];
  282. }
  283. $book['url'] = $urlBook;
  284. $book['image'] = $cover;
  285. if ($promotionNum == 0) {
  286. //第一条图片选用图库中的图片地址
  287. $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
  288. if ($promotionImages) {
  289. $book['image'] = $promotionImages[0]['link'];
  290. } else {
  291. $book['image'] = $cover;
  292. }
  293. } else {
  294. $book['image'] = $cover;
  295. }
  296. $booksArray[] = [['title' => $book['title']], ['description' => $book['description']], ['url' => $book['url']], ['image' => $book['image']]];
  297. $promotionNum++;
  298. }
  299. //9,通过RebitMQ推送热门书籍到指定用户
  300. $data = array();
  301. $data['openid'] = $force_user[$i]['openid'];
  302. $data['appid'] = $force_user[$i]['appid'];
  303. $data['news_content'] = json_encode($booksArray);
  304. $data['type'] = 'one_task';
  305. $data['task_id'] = 3;
  306. $data['send_time'] = date("Y-m-d H:i:s");
  307. $send_data = array(
  308. 'send_time' => date("Y-m-d H:i:s"),
  309. 'data' => $data
  310. );
  311. $delay = 0;
  312. //\Log::info('<---- 客服消息发送内容 参数---->');
  313. //\Log::info($data['openid']);
  314. //\Log::info($data['appid']);
  315. //\Log::info($data['news_content']);
  316. //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');
  317. $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
  318. dispatch($job);
  319. Redis::hset('add_news_recovery_push_hot' . $uid, 'time', time());
  320. }
  321. }
  322. }
  323. }
  324. }
  325. }
  326. }
  327. /**
  328. * 三天回本推送(定时任务 24小时推)
  329. */
  330. static function add_news_recovery_push_activity()
  331. {
  332. \Log::info('=======================三天回本推送客服消息');
  333. //1,遍历渠道表
  334. $distribution_channels = ChannelService::getAllChannels();
  335. $customPushActivitys = CustomPushActivitys::customPushActivitys();
  336. $custom_url = $customPushActivitys['url'];
  337. $custom_image = $customPushActivitys['image'];
  338. $custom_title = $customPushActivitys['title'];
  339. for ($k = 0; $k < count($distribution_channels); $k++) {
  340. //2,判断该渠道下有没有开启 未支付订单的智能推送
  341. $distribution_channel_id = $distribution_channels[$k]['id'];
  342. $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id, 'recovery_push');
  343. if (!empty($customMsgSwitch)) {
  344. if ($customMsgSwitch['status'] == '1') {
  345. //\Log::info('<----开启客服的 渠道号---->');
  346. //\Log::info($distribution_channel_id);
  347. //3,开通智能推送的渠道获取 渠道下的强关用户
  348. $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;
  349. $forceSubscribeUsersPrams['timeset'] = 86400;
  350. $force_user = ForceSubscribeService::forceSubscribeNewUsersByTimeset($forceSubscribeUsersPrams);
  351. //\Log::info('<----渠道下强关用户数---->');
  352. //\Log::info(count($force_user));
  353. $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id, 'recovery_push', date("Y-m-d"));
  354. if (empty($customSendStatsCount)) {
  355. $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
  356. $customSendDayStats['from'] = 'recovery_push';
  357. $customSendDayStats['push_user_num'] = count($force_user);
  358. $customSendDayStats['date'] = date("Y-m-d");
  359. CustomSendDayStats::create($customSendDayStats);
  360. } else {
  361. $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num'] + count($force_user);
  362. $customSendStatsCount->save();
  363. }
  364. for ($i = 0; $i < count($force_user); $i++) {
  365. //(1)通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息
  366. //(2)如果有,获取插入的时间,
  367. // 如果时间在今天之内,那就不发送,
  368. // 如果不是,就发送,并往Redis中插入一条数据
  369. $uid = $force_user[$i]['uid'];
  370. if (!Redis::hget('add_news_recovery_push_activity' . $uid, 'time')) {
  371. //9,通过RebitMQ推送热门书籍到指定用户
  372. $data = array();
  373. $data['openid'] = $force_user[$i]['openid'];
  374. $data['appid'] = $force_user[$i]['appid'];
  375. $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com' . $custom_url;
  376. $data['news_content'] = '[[{"title":"' . $custom_title . '"},{"description":""},{"url":"' . $url . '"},{"image":"' . $custom_image . '"}]]';
  377. $data['type'] = 'one_task';
  378. $data['task_id'] = 3;
  379. $data['send_time'] = date("Y-m-d H:i:s");
  380. $send_data = array(
  381. 'send_time' => date("Y-m-d H:i:s"),
  382. 'data' => $data
  383. );
  384. $delay = 0;
  385. //\Log::info('<---- 客服消息发送内容 参数---->');
  386. //\Log::info($data['openid']);
  387. //\Log::info($data['appid']);
  388. //\Log::info($data['news_content']);
  389. //\Log::info('<----Rebit-MQ 发送三天回本活动推送---->');
  390. $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
  391. // $job = (new SendNews($send_data))->onConnection('redis')->delay($delay)->onQueue('send_news_list');
  392. dispatch($job);
  393. Redis::hset('add_news_recovery_push_activity' . $uid, 'time', time());
  394. }
  395. }
  396. }
  397. }
  398. }
  399. }
  400. /**
  401. * 未充值用户推送客服消息(24-48小时内关注)(定时任务)
  402. */
  403. static function unPaidUserActivity()
  404. {
  405. \Log::info('=======================未充值用户推荐客服消息');
  406. //1,遍历渠道表
  407. $distribution_channels = ChannelService::getAllChannels();
  408. for ($k = 0; $k < count($distribution_channels); $k++) {
  409. //2,判断该渠道下有没有开启 未支付订单的智能推送
  410. $distribution_channel_id = $distribution_channels[$k]['id'];
  411. // 嘉言小说
  412. // if(!in_array($distribution_channel_id,array('2'))){
  413. // // \Log::info('unPaidUserActivity_continue,$distribution_channel_id:'.$distribution_channel_id);
  414. // continue;
  415. // }
  416. $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id, 'unpaid_send_activity');
  417. if (!empty($customMsgSwitch)) {
  418. if ($customMsgSwitch['status'] == '1') {
  419. //\Log::info('<----开启未付费推送的 渠道号---->:'.$distribution_channel_id);
  420. //3,开通智能推送的渠道获取 渠道下的强关用户
  421. $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;
  422. $forceSubscribeUsersPrams['start_time'] = date('Y-m-d H:i:s', strtotime('-2 day'));
  423. $forceSubscribeUsersPrams['end_time'] = date('Y-m-d H:i:s', strtotime('-1 day'));
  424. $force_user = ForceSubscribeService::forceSubscribeNewUnpaidUsersByTime($forceSubscribeUsersPrams);
  425. //\Log::info('<----渠道下强关用户数---->');
  426. //\Log::info($force_user);
  427. //\Log::info(count($force_user));
  428. $push_user_num = 0;
  429. for ($i = 0; $i < count($force_user); $i++) {
  430. //(1)通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息
  431. //(2)如果有,获取插入的时间,
  432. // 每个新关用户只发送一次
  433. // 如果不是,就发送,并往Redis中插入一条数据
  434. $uid = $force_user[$i]['uid'];
  435. if (!Redis::hget('unpaid_send_activity_uid:' . $uid, 'time')) {
  436. $bid = $force_user[$i]['bid'];
  437. $data = array();
  438. $data['openid'] = $force_user[$i]['openid'];
  439. $data['appid'] = $force_user[$i]['appid'];
  440. //活动链接
  441. $continueReadUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time=' . time();
  442. $data['content'] = '您的新用户专享礼包已送达' . "\n\n" . '充9.9元,得2000书币,只有一次机会哦!' . "\n\n" . '过期失效,不要错过!' . "\n\n" . '<a href="' . $continueReadUrl . '">点击立即领取> ></a>' . "\n\n" . '为方便下次阅读,请' . '<a href="https://help.leyuee.com/top.html">' . '置顶公众号' . '</a>';
  443. $data['type'] = 'one_task';// last_task,one_task
  444. $data['task_id'] = 1;
  445. $data['send_time'] = date("Y-m-d H:i:s");
  446. $send_data = array(
  447. 'send_time' => date("Y-m-d H:i:s"),
  448. 'data' => $data
  449. );
  450. //\Log::info('unpaid_send_activity_openid:'.$data['openid'].' appid:'.$data['appid'].' content:'.$data['content']);
  451. $delay = 0;
  452. $job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list');
  453. dispatch($job);
  454. Redis::hset('unpaid_send_activity_uid:' . $uid, 'time', time());
  455. Redis::EXPIRE('unpaid_send_activity_uid:' . $uid, 86400);
  456. //\Log::info('unpaid_send_activity_settime_uid:'.$uid.' time:'.time());
  457. $push_user_num++;
  458. } else {
  459. \Log::info('unpaid_send_activity_exist_uid:' . $force_user[$i]['uid'] . ' time:' . Redis::hget('unpaid_send_activity_uid:' . $uid, 'time'));
  460. }
  461. }
  462. \Log::info('unpaid_send_activity,push_user_num:' . $push_user_num);
  463. // 因为有些用户重复筛选,所以人数在后面更新
  464. $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id, 'unpaid_send_activity', date("Y-m-d"));
  465. if (empty($customSendStatsCount)) {
  466. $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
  467. $customSendDayStats['from'] = 'unpaid_send_activity';
  468. $customSendDayStats['push_user_num'] = $push_user_num;
  469. $customSendDayStats['date'] = date("Y-m-d");
  470. CustomSendDayStats::create($customSendDayStats);
  471. } else {
  472. $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num'] + $push_user_num;
  473. $customSendStatsCount->save();
  474. }
  475. } else {
  476. \Log::info('<----未开启 未付费推送的 渠道号---->:' . $distribution_channel_id);
  477. }
  478. }
  479. }
  480. }
  481. /**
  482. * 客服消息智能推送方法--公用版
  483. * 以下3个板块找到对应的推送
  484. * 1、用户
  485. * 2、内容
  486. * 3、队列类型
  487. */
  488. static function SmartPush($category_type)
  489. {
  490. if (empty($category_type)) return false;
  491. $base_category_type = self::get_base_category_type($category_type);
  492. \Log::info('smart_push:' . $category_type . ' base_category_type:' . $base_category_type);
  493. // 先更新书库和测书信息,避免频繁查询
  494. BookConfigService::resetBookLibRedis($category_type);
  495. //1,遍历渠道表
  496. $distribution_channels = ChannelService::getAllChannels();
  497. for ($k = 0; $k < count($distribution_channels); $k++) {
  498. //2,判断该渠道下有没有开启 未支付订单的智能推送
  499. $distribution_channel_id = $distribution_channels[$k]['id'];
  500. $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id, $base_category_type);
  501. if (!empty($customMsgSwitch)) {
  502. if ($customMsgSwitch['status'] == '1') {
  503. \Log::info('SmartPush_channel_id:' . $distribution_channel_id . ' category_type:' . $category_type . ' is_self_content:' . $customMsgSwitch['is_self_content']);
  504. // 如果自定义内容发送
  505. $sexs = array('z');
  506. if ($customMsgSwitch['is_self_content']) {
  507. $sexs = array('a', 'b');
  508. }
  509. $user_total_count = 0;
  510. foreach ($sexs as $sex) {
  511. \Log::info('smart_push_sex:' . $sex);
  512. $smartPushsMsg = array();
  513. $smartPushsMsg['distribution_channel_id'] = $distribution_channel_id;
  514. $smartPushsMsg['category_type'] = $category_type;
  515. $smartPushsMsg['sex'] = $sex;
  516. $send_content = '';
  517. if ($customMsgSwitch['is_self_content']) {
  518. $smartPushsMsgData = SmartPushMsgService::smartPushByDistributionChannelIdAndCategorySex($smartPushsMsg);
  519. //\Log::info('$smartPushsMsgData:');
  520. //\Log::info($smartPushsMsgData);
  521. if (!empty($smartPushsMsgData)) {
  522. // 带上参数
  523. $send_content = TemplateCustomSendService::convert_custom_content($smartPushsMsgData->content, 'smart_push_' . $base_category_type, $distribution_channel_id, 0);
  524. $send_content = json_decode($send_content);
  525. }
  526. }
  527. $skip = 0;
  528. $loop = 0;
  529. while ($skip <= 250000) {
  530. $loop++;
  531. $force_user = null;
  532. $force_user = self::get_send_force_users($distribution_channel_id, $category_type, $sex, $skip);
  533. \Log::info('SmartPush_usernum:' . count($force_user) . ' loop:' . $loop . ' distribution_channel_id:' . $distribution_channel_id . ' memory:' . memory_get_usage());
  534. $force_user_num = count($force_user);
  535. $skip += $force_user_num;
  536. $user_total_count += $force_user_num;
  537. if ($force_user_num > 0) {
  538. for ($i = 0; $i < $force_user_num; $i++) {
  539. $uid = $force_user[$i]['uid'];
  540. $bid = $force_user[$i]['bid'];
  541. if (empty($bid)) $bid = 1;// TODO
  542. // 非自定义,则根据bid取系统推荐的书籍
  543. if (empty($customMsgSwitch['is_self_content'])) {
  544. \Log::info('get_user_send_content_start');
  545. $send_content = null;
  546. $send_content = self::get_user_send_content($bid, $distribution_channel_id, $category_type, $uid);
  547. } else {
  548. \Log::info('get_user_send_content_not_start:' . $uid . ' memory:' . memory_get_usage());
  549. }
  550. if (empty($send_content)) {
  551. \Log::info('smart_push:openid:' . $force_user[$i]['openid'] . ' appid:' . $force_user[$i]['appid'] . ' content_is_null');
  552. continue;
  553. }
  554. $smart_push_queue = self::get_smart_push_queue($category_type);
  555. $data = array();
  556. $data['openid'] = $force_user[$i]['openid'];
  557. $data['appid'] = $force_user[$i]['appid'];
  558. if (isset($smart_push_queue['is_news']) && $smart_push_queue['is_news']) {
  559. $data[$smart_push_queue['content']] = json_encode($send_content);
  560. } else {
  561. $data[$smart_push_queue['content']] = $send_content;
  562. }
  563. $data['type'] = 'one_task';
  564. $data['task_id'] = 3;
  565. $data['send_time'] = date("Y-m-d H:i:s");
  566. $send_data = array(
  567. 'send_time' => date("Y-m-d H:i:s"),
  568. 'data' => $data
  569. );
  570. $delay = 0;
  571. // \Log::info('smart_push:'.json_encode($data));
  572. if (isset($smart_push_queue['is_news']) && $smart_push_queue['is_news']) {
  573. $job = (new SendSmartNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
  574. } else {
  575. $job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
  576. }
  577. dispatch($job);
  578. \Log::info('smart_push_user_end:' . $uid . ' memory:' . memory_get_usage());
  579. // 释放内存
  580. $send_data = $data = null;
  581. }//end users
  582. if ($force_user_num < 10000)//低于单次获取的10000条,所以下次不必获取,必须与单次获取的数值保持一致!
  583. {
  584. \Log::info('smart_push user num less than once get num, so break ,distribution_channel_id:' . $distribution_channel_id . ' category_type:' . $category_type . ' sex:' . $sex . ' loop:' . $loop . ' memory:' . memory_get_usage());
  585. break;
  586. }
  587. } else {
  588. \Log::info('smart_push_has_no_user,distribution_channel_id:' . $distribution_channel_id . ' category_type:' . $category_type . ' sex:' . $sex . ' loop:' . $loop . ' memory:' . memory_get_usage());
  589. break;
  590. }
  591. }
  592. } // end sex
  593. \Log::info('SmartPush_end:' . ' distribution_channel_id:' . $distribution_channel_id . ' memory:' . memory_get_usage());
  594. // 后面计数
  595. $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id, $base_category_type, date("Y-m-d"));
  596. if (empty($customSendStatsCount)) {
  597. $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
  598. $customSendDayStats['from'] = $base_category_type;
  599. $customSendDayStats['push_user_num'] = $user_total_count;
  600. $customSendDayStats['date'] = date("Y-m-d");
  601. CustomSendDayStats::create($customSendDayStats);
  602. } else {
  603. $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num'] + $user_total_count;
  604. $customSendStatsCount->save();
  605. }
  606. }
  607. }// end 开关
  608. }
  609. }
  610. static function get_base_category_type($category_type)
  611. {
  612. if ($category_type == 'unpaid_hot_push' || $category_type == 'all_hot_push') {
  613. return 'hot_push';
  614. }
  615. if ($category_type == 'paid_point_push' || $category_type == 'unpaid_point_push') {
  616. return 'point_push';
  617. }
  618. if ($category_type == 'unpaid_send_big_activity') {
  619. return 'unpaid_send_activity';
  620. }
  621. return $category_type;
  622. }
  623. static function get_smart_push_queue($category_type)
  624. {
  625. $smart_push_queue = array();
  626. $text_queue = array('unpaid_send_activity', 'unpaid_send_big_activity', 'pay_daily_push');
  627. if (in_array($category_type, $text_queue)) {
  628. $smart_push_queue['is_news'] = false;
  629. $smart_push_queue['content'] = 'content';
  630. $smart_push_queue['queue'] = 'send_texts_list';
  631. } else {
  632. $smart_push_queue['is_news'] = true;
  633. $smart_push_queue['content'] = 'news_content';
  634. $smart_push_queue['queue'] = 'send_smartnews_list';
  635. }
  636. // \Log::info('$smart_push_queue');\Log::info($smart_push_queue);
  637. return $smart_push_queue;
  638. }
  639. static function get_base_custom_param()
  640. {
  641. $param = array();
  642. $param['appids'] = array();
  643. $param['subscribe_time'] = 'z';
  644. $param['sex'] = 'z';
  645. $param['balance'] = 'z';
  646. $param['category_id'] = 'z';
  647. $param['order_type'] = 'z';
  648. $param['sign_time'] = 'z';
  649. //$param['skip'] = 0;
  650. return $param;
  651. }
  652. static function get_appids_str($distribution_channel_id)
  653. {
  654. $official_accounts = OfficialAccount::officialAuthAccountBydistributionChannelId($distribution_channel_id, 1, 1);
  655. $appids = array();
  656. foreach ($official_accounts as $official_account) {
  657. $appids[] = $official_account->appid;
  658. }
  659. $appids_str = implode(',', $appids);
  660. return $appids_str;
  661. }
  662. /**
  663. * 去重筛选的用户,已经推送过的不再推送
  664. * @param unknown_type $force_users
  665. * @param unknown_type $redis_pre_str
  666. */
  667. static function get_unique_users($force_users, $redis_pre_str, $expire_time = 3600)
  668. {
  669. // 去重
  670. if (!empty($force_users)) {
  671. \Log::info('before_' . $redis_pre_str . '_quchong::' . count($force_users));
  672. foreach ($force_users as $key => $force_user) {
  673. $uid = $force_user['uid'];
  674. $appid = $force_user['appid'];
  675. $user_key = $redis_pre_str . ':' . $uid;
  676. $user_appid_key = $redis_pre_str . ':' . $appid . ':' . $uid;
  677. // 兼容老逻辑
  678. if (Redis::get($user_key)) {
  679. unset($force_users[$key]);
  680. // \Log::info($redis_pre_str.'_exist_user:'.$uid);
  681. continue;
  682. } // appid级别的
  683. elseif (Redis::get($user_appid_key)) {
  684. unset($force_users[$key]);
  685. // \Log::info($redis_pre_str.'_exist_user:'.$uid);
  686. continue;
  687. } else {
  688. // \Log::info($redis_pre_str.'_push_add_user:'.$uid);
  689. // 以后都按appid级别来
  690. Redis::SETEX($user_appid_key, $expire_time, date('Y-m-d H:i:s'));
  691. }
  692. }
  693. \Log::info('after_' . $redis_pre_str . '_push_quchong::' . count($force_users));
  694. }
  695. return $force_users;
  696. }
  697. /**
  698. * 得到指定类型智能推送发送的用户列表
  699. */
  700. static function get_send_force_users($distribution_channel_id, $category_type, $sex, $skip = 0)
  701. {
  702. $force_users = array();
  703. $custom_param = self::get_base_custom_param();
  704. $custom_param['skip'] = $skip;//skip传进来
  705. $custom_param['distribution_channel_id'] = $distribution_channel_id;
  706. $custom_param['appids'] = self::get_appids_str($distribution_channel_id);
  707. $custom_param['sex'] = $sex;
  708. // 签到推送
  709. if ($category_type == 'sign_push') {
  710. $custom_param['sign_time'] = 'a';// 60-120分钟内
  711. $custom_param['subscribe_time'] = 'g';// 1天前老用户
  712. $force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'], $custom_param['distribution_channel_id'], $custom_param['subscribe_time'], $custom_param['sex'], $custom_param['balance'], $custom_param['category_id'], $custom_param['order_type'], $custom_param['sign_time'], $custom_param['skip']);
  713. $force_users = self::get_unique_users($force_users, 'sign_push_user', 7200);
  714. } // 关注推送
  715. elseif ($category_type == 'subscribe_push') {
  716. $custom_param['subscribe_time'] = 'h';// 10-50分钟内
  717. $force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'], $custom_param['distribution_channel_id'], $custom_param['subscribe_time'], $custom_param['sex'], $custom_param['balance'], $custom_param['category_id'], $custom_param['order_type'], $custom_param['sign_time'], $custom_param['skip']);
  718. $force_users = self::get_unique_users($force_users, 'subscribe_push_user', 3600);
  719. } // 全量热门书籍推送
  720. elseif ($category_type == 'all_hot_push') {
  721. $custom_param['subscribe_time'] = 'l';//12-48小时
  722. $custom_param['order_type'] = 'z';//全量
  723. $force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'], $custom_param['distribution_channel_id'], $custom_param['subscribe_time'], $custom_param['sex'], $custom_param['balance'], $custom_param['category_id'], $custom_param['order_type'], $custom_param['sign_time'], $custom_param['skip']);
  724. $force_users = self::get_unique_users($force_users, 'all_hot_push', 3600 * 48);
  725. } // 已付费定制书籍推送
  726. elseif ($category_type == 'paid_point_push') {
  727. $custom_param['subscribe_time'] = 'k';//42-48小时
  728. $custom_param['order_type'] = 'b';//已充值
  729. $force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'], $custom_param['distribution_channel_id'], $custom_param['subscribe_time'], $custom_param['sex'], $custom_param['balance'], $custom_param['category_id'], $custom_param['order_type'], $custom_param['sign_time'], $custom_param['skip']);
  730. $force_users = self::get_unique_users($force_users, 'paid_point_push', 3600 * 48);
  731. // 排除测试的用户
  732. // $force_users = self::get_minus_test_users($force_users);
  733. } // 未付费热门书籍推送
  734. elseif ($category_type == 'unpaid_hot_push') {
  735. $custom_param['subscribe_time'] = 'f';//24-48小时
  736. $custom_param['order_type'] = 'a';//未充值
  737. $force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'], $custom_param['distribution_channel_id'], $custom_param['subscribe_time'], $custom_param['sex'], $custom_param['balance'], $custom_param['category_id'], $custom_param['order_type'], $custom_param['sign_time'], $custom_param['skip']);
  738. $force_users = self::get_unique_users($force_users, 'unpaid_hot_push', 3600 * 48);
  739. } // 未付费定制书籍推送
  740. elseif ($category_type == 'unpaid_point_push') {
  741. $custom_param['subscribe_time'] = 'k';//42-48小时
  742. $custom_param['order_type'] = 'a';//未充值
  743. $force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'], $custom_param['distribution_channel_id'], $custom_param['subscribe_time'], $custom_param['sex'], $custom_param['balance'], $custom_param['category_id'], $custom_param['order_type'], $custom_param['sign_time'], $custom_param['skip']);
  744. $force_users = self::get_unique_users($force_users, 'unpaid_point_push', 3600 * 48);
  745. // 排除测试的用户
  746. // $force_users = self::get_minus_test_users($force_users);
  747. } // 未付费优惠充值活动推送(多选项)
  748. elseif ($category_type == 'unpaid_send_big_activity') {
  749. $custom_param['subscribe_time'] = 'j';//20-48小时
  750. $custom_param['order_type'] = 'a';//未充值
  751. $force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'], $custom_param['distribution_channel_id'], $custom_param['subscribe_time'], $custom_param['sex'], $custom_param['balance'], $custom_param['category_id'], $custom_param['order_type'], $custom_param['sign_time'], $custom_param['skip']);
  752. $force_users = self::get_unique_users($force_users, 'unpaid_send_big_activity', 3600 * 48);
  753. } // 未付费9.9活动推送
  754. elseif ($category_type == 'unpaid_send_activity') {
  755. $custom_param['subscribe_time'] = 'i';//36-48小时
  756. $custom_param['order_type'] = 'a';//未充值
  757. $force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'], $custom_param['distribution_channel_id'], $custom_param['subscribe_time'], $custom_param['sex'], $custom_param['balance'], $custom_param['category_id'], $custom_param['order_type'], $custom_param['sign_time'], $custom_param['skip']);
  758. $force_users = self::get_unique_users($force_users, 'unpaid_send_activity', 3600 * 48);
  759. } // 付费用户推送
  760. elseif ($category_type == 'pay_daily_push') {
  761. $custom_param['order_type'] = 'd';//6-13小时充值,考虑到0-6点不推送
  762. $force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'], $custom_param['distribution_channel_id'], $custom_param['subscribe_time'], $custom_param['sex'], $custom_param['balance'], $custom_param['category_id'], $custom_param['order_type'], $custom_param['sign_time'], $custom_param['skip']);
  763. $force_users = self::get_unique_users($force_users, 'pay_daily_push', 3600 * 24);
  764. } else {
  765. }
  766. // key重新排序
  767. $temp_force_users = array();
  768. if (!empty($force_users)) {
  769. foreach ($force_users as $force_user) {
  770. $temp_force_users[] = $force_user;
  771. }
  772. }
  773. return $temp_force_users;
  774. }
  775. /**
  776. * 得到指定用户,发送的图文内容
  777. */
  778. static function get_user_send_content($bid, $distribution_channel_id, $category_type, $uid)
  779. {
  780. $send_content = '';
  781. $recommend_book_category_types = array('sign_push', 'subscribe_push');
  782. // 改版,书籍数量只能选1本
  783. $send_book_num = 1;
  784. // 推荐图书
  785. if (in_array($category_type, $recommend_book_category_types)) {
  786. $send_content = self::get_user_recommend_books($bid, $distribution_channel_id, $send_book_num, $category_type, $uid);
  787. } // 已付费热门书籍推送 12小时
  788. elseif ($category_type == 'all_hot_push') {
  789. $send_content = self::get_user_recommend_books($bid, $distribution_channel_id, $send_book_num, $category_type, $uid);
  790. } // 未付费热门书籍推送 24小时
  791. elseif ($category_type == 'unpaid_hot_push') {
  792. // 优惠充值活动
  793. $send_content = array();
  794. $send_content[] = [
  795. ['title' => '新用户专享:点此领取25000书币'],
  796. ['description' => '新用户专享:点此领取25000书币'],
  797. ['url' => env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time=' . time()],
  798. ['image' => 'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/citiao.jpg']
  799. ];
  800. } // 已付费定制书籍推送 42小时
  801. elseif ($category_type == 'paid_point_push') {
  802. $send_content = self::get_user_recommend_books($bid, $distribution_channel_id, $send_book_num, $category_type, $uid);
  803. } // 未付费定制书籍推送 42小时
  804. elseif ($category_type == 'unpaid_point_push') {
  805. $send_content = array();
  806. if (in_array($distribution_channel_id, array('14'))) {
  807. // 头条为终身充值活动
  808. $first_activity = [
  809. ['title' => '全年免费看书的机会来啦!限时优惠'],
  810. ['description' => '全年免费看书的机会来啦!限时优惠'],
  811. ['url' => env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/seYearActivity?fromtype=unpaid_send_activity&send_time=' . time()],
  812. ['image' => 'https://cdn-novel.iycdm.com/h5/2018111201.jpg']
  813. ];
  814. } else {
  815. // 头条为9.9元活动
  816. $first_activity = [
  817. ['title' => '充9.9元,得2000书币!'],
  818. ['description' => '充9.9元,得2000书币,只有一次机会哦!过期失效,不要错过!'],
  819. ['url' => env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time=' . time()],
  820. ['image' => 'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/toutiao.jpg']
  821. ];
  822. }
  823. $send_content[] = $first_activity;
  824. } // 未付费优惠充值活动推送(多选项)
  825. elseif ($category_type == 'unpaid_send_big_activity') {
  826. //活动链接
  827. $continueReadUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time=' . time();
  828. $send_content = '您的新用户专享礼包已送达' . "\n\n" . '送25000书币及优惠券,畅读全站小说无压力!' . "\n\n" . '过期失效,只有1次机会哦!' . "\n\n" . '<a href="' . $continueReadUrl . '">点击立即领取> ></a>' . "\n\n" . '为方便下次阅读,请' . '<a href="https://help.leyuee.com/top.html">' . '置顶公众号' . '</a>';
  829. } // 未付费9.9活动推送
  830. elseif ($category_type == 'unpaid_send_activity') {
  831. //活动链接
  832. $continueReadUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time=' . time();
  833. $send_content = '您的新用户专享礼包已送达' . "\n\n" . '充9.9元,得2000书币,只有一次机会哦!' . "\n\n" . '过期失效,不要错过!' . "\n\n" . '<a href="' . $continueReadUrl . '">点击立即领取> ></a>' . "\n\n" . '为方便下次阅读,请' . '<a href="https://help.leyuee.com/top.html">' . '置顶公众号' . '</a>';
  834. } // 付费用户推送
  835. elseif ($category_type == 'pay_daily_push') {
  836. $userBook = ReadRecordService::getFirstReadRecord($uid);
  837. $book_name = isset($userBook['book_name']) ? $userBook['book_name'] : '';
  838. $user = UserService::getById($uid);
  839. $balance = isset($user->balance) ? $user->balance : '0';
  840. $nickname = isset($user->nickname) ? $user->nickname : '';
  841. //用户最近阅读链接
  842. $continueReadUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/continue?fromtype=pay_daily_push';
  843. //拼接文案
  844. if (empty($book_name)) {
  845. $send_content = '尊敬的会员:' . $nickname . "\n\n" . '您的账户余额:' . $balance . "\n\n" . '<a href="' . $continueReadUrl . '">点击继续阅读~</a>' . "\n";
  846. } else {
  847. $send_content = '尊敬的会员:' . $nickname . "\n\n" . '您的账户余额:' . $balance . "\n\n" . '最近阅读书籍:《' . $book_name . '》' . "\n\n" . '<a href="' . $continueReadUrl . '">点击继续阅读~</a>' . "\n";
  848. }
  849. \Log::info('pay_daily_push_send_content:' . $uid);
  850. \Log::info($send_content);
  851. } // TODO最近阅读?
  852. else {
  853. }
  854. return $send_content;
  855. }
  856. /**
  857. * 得到指定用户,发送的图文内容
  858. * 多条图文版--老版
  859. */
  860. static function get_user_send_content_multy($bid, $distribution_channel_id, $category_type, $uid)
  861. {
  862. $send_content = '';
  863. $recommend_book_category_types = array('sign_push', 'subscribe_push');
  864. // 推荐图书
  865. if (in_array($category_type, $recommend_book_category_types)) {
  866. $send_content = self::get_user_recommend_books($bid, $distribution_channel_id, 4, $category_type, $uid);
  867. } // 已付费热门书籍推送 12小时
  868. elseif ($category_type == 'all_hot_push') {
  869. $send_content = self::get_user_recommend_books($bid, $distribution_channel_id, 5, $category_type, $uid);
  870. } // 未付费热门书籍推送 24小时
  871. elseif ($category_type == 'unpaid_hot_push') {
  872. // 次条增加优惠充值活动
  873. $send_content_temp = self::get_user_recommend_books($bid, $distribution_channel_id, 4, $category_type, $uid);
  874. $send_content = array();
  875. $send_content[0] = $send_content_temp[0];
  876. $send_content[1] = [
  877. ['title' => '新用户专享:点此领取25000书币'],
  878. ['description' => '新用户专享:点此领取25000书币'],
  879. ['url' => env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time=' . time()],
  880. ['image' => 'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/citiao.jpg']
  881. ];
  882. $send_content[2] = $send_content_temp[1];
  883. $send_content[3] = $send_content_temp[2];
  884. $send_content[4] = $send_content_temp[3];
  885. } // 已付费定制书籍推送 42小时
  886. elseif ($category_type == 'paid_point_push') {
  887. // 头条为最近阅读记录链接
  888. $recent_read_book = self::get_user_recent_read_books($uid, $distribution_channel_id, $category_type);
  889. $send_content = self::get_user_recommend_books($bid, $distribution_channel_id, 4, $category_type, $uid);
  890. array_unshift($send_content, $recent_read_book);// 前插
  891. } // 未付费定制书籍推送 42小时
  892. elseif ($category_type == 'unpaid_point_push') {
  893. $send_content = self::get_user_recommend_books($bid, $distribution_channel_id, 3, $category_type, $uid);
  894. // 次条为最近阅读记录链接
  895. $recent_read_book = self::get_user_recent_read_books($uid, $distribution_channel_id, $category_type);
  896. array_unshift($send_content, $recent_read_book);
  897. // 头条为9.9元活动
  898. $first_activity = [
  899. ['title' => '充9.9元,得2000书币!'],
  900. ['description' => '充9.9元,得2000书币,只有一次机会哦!过期失效,不要错过!'],
  901. ['url' => env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time=' . time()],
  902. ['image' => 'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/toutiao.jpg']
  903. ];
  904. array_unshift($send_content, $first_activity);
  905. } // 未付费优惠充值活动推送(多选项)
  906. elseif ($category_type == 'unpaid_send_big_activity') {
  907. //活动链接
  908. $continueReadUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time=' . time();
  909. $send_content = '您的新用户专享礼包已送达' . "\n\n" . '送25000书币及优惠券,畅读全站小说无压力!' . "\n\n" . '过期失效,只有1次机会哦!' . "\n\n" . '<a href="' . $continueReadUrl . '">点击立即领取> ></a>' . "\n\n" . '为方便下次阅读,请' . '<a href="https://help.leyuee.com/top.html">' . '置顶公众号' . '</a>';
  910. } // 未付费9.9活动推送
  911. elseif ($category_type == 'unpaid_send_activity') {
  912. //活动链接
  913. $continueReadUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time=' . time();
  914. $send_content = '您的新用户专享礼包已送达' . "\n\n" . '充9.9元,得2000书币,只有一次机会哦!' . "\n\n" . '过期失效,不要错过!' . "\n\n" . '<a href="' . $continueReadUrl . '">点击立即领取> ></a>' . "\n\n" . '为方便下次阅读,请' . '<a href="https://help.leyuee.com/top.html">' . '置顶公众号' . '</a>';
  915. } // TODO最近阅读?
  916. else {
  917. }
  918. return $send_content;
  919. }
  920. /**
  921. * 得到指定用户,系统推荐的书籍列表
  922. */
  923. static function get_user_recommend_books($bid, $distribution_channel_id, $book_num = 4, $category_type, $uid)
  924. {
  925. $base_category_type = self::get_base_category_type($category_type);
  926. \Log::info('get_user_recommend_books,bid:' . $bid . ' distribution_channel_id:' . $distribution_channel_id . ' book_num:' . $book_num . ' uid:' . $uid . ' base_category_type:' . $base_category_type . ' category_type:' . $category_type);
  927. // $books = BookConfigService::getSimpleChannelBook($bid,$book_num);
  928. $books = BookConfigService::getSimpleChannelBookLoop($bid, $book_num, $uid);
  929. $bookUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com';
  930. $booksArray = [];
  931. // 标题加余额
  932. $pre_title = '';
  933. if (in_array($distribution_channel_id, array('123', '211', '14'))) {
  934. $user = UserService::getById($uid);
  935. $balance = isset($user->balance) ? $user->balance : '0';
  936. if ($balance >= 100) {
  937. $pre_title = '您的账户余额:' . $balance . '书币 ';
  938. }
  939. }
  940. //5,获取男频女频的标签文案
  941. $womanPromotion = PromotionService::getRandomHeadline(2, count($books));
  942. $manPromotion = PromotionService::getRandomHeadline(1, count($books));
  943. $promotionNum = 0;
  944. if ($books) {
  945. foreach ($books as $key => $value) {
  946. // 标题图片id标识
  947. $title_image = [];
  948. $channelName = $value->channel_name;
  949. $cover = $value->cover;
  950. if ($channelName == '男频') {
  951. $book['title'] = $manPromotion[$promotionNum]['title'];
  952. $book['description'] = $manPromotion[$promotionNum]['title'];
  953. $title_image['title_id'] = $manPromotion[$promotionNum]['id'];
  954. } else {
  955. $book['title'] = $womanPromotion[$promotionNum]['title'];
  956. $book['description'] = $womanPromotion[$promotionNum]['title'];
  957. $title_image['title_id'] = $womanPromotion[$promotionNum]['id'];
  958. }
  959. if ($promotionNum == 0) {
  960. //第一条图片选用图库中的图片地址
  961. $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
  962. if ($promotionImages) {
  963. $book['image'] = $promotionImages[0]['link'];
  964. $title_image['image_id'] = $promotionImages[0]['id'];
  965. } else {
  966. $book['image'] = $cover;
  967. $title_image['image_id'] = 0;
  968. }
  969. } else {
  970. $book['image'] = $cover;
  971. $title_image['image_id'] = 0;
  972. }
  973. // 记录标题图片推送的redis
  974. $title_image_key = $title_image['title_id'] . '_' . $title_image['image_id'];
  975. \Log::info('title_image_smart_push:' . $base_category_type . ' uid:' . $uid . ' title_image_key:' . $title_image_key);
  976. $title_image_send_uv_key = 'smart_push_from_title_image_send_uv:' . $title_image_key;
  977. $title_image_statistics_key = 'smart_push_from_title_image:' . $title_image_key;
  978. Redis::sadd($title_image_send_uv_key, $uid);
  979. Redis::HINCRBY($title_image_statistics_key, 'send_num', 1);
  980. //通过判断书籍是男频还是女频拼接书籍信息的不同标签文案
  981. if (strpos($bookUrl . $value->url, '?') > -1) {
  982. $urlBook = $value->url = $bookUrl . $value->url . '&fromtype=' . $base_category_type . '&source=wechatmsg&fromsource=smart_push&from_title_image=' . $title_image_key;
  983. } else {
  984. $urlBook = $value->url = $bookUrl . $value->url . '?fromtype=' . $base_category_type . '&source=wechatmsg&fromsource=smart_push&from_title_image=' . $title_image_key;
  985. }
  986. $book['url'] = $urlBook;
  987. // $book['image'] = $cover;
  988. if (!empty($pre_title)) {
  989. $book['title'] = $pre_title . $book['title'];
  990. }
  991. $booksArray[$key] = [['title' => $book['title']], ['description' => $book['description']], ['url' => $book['url']], ['image' => $book['image']]];
  992. $promotionNum++;
  993. }
  994. }
  995. return $booksArray;
  996. }
  997. /**
  998. * 得到用户最近阅读的记录
  999. */
  1000. static function get_user_recent_read_books($uid, $distribution_channel_id, $category_type)
  1001. {
  1002. \Log::info('get_user_recent_read_books,distribution_channel_id:' . $distribution_channel_id . ' uid:' . $uid);
  1003. $base_category_type = self::get_base_category_type($category_type);
  1004. $booksArray = [];
  1005. // 获取用户最近阅读的书籍信息
  1006. $userBook = ReadRecordService::getFirstReadRecord($uid);
  1007. if ($userBook) {
  1008. $book = array();
  1009. $book['url'] = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/continue?fromtype=' . $base_category_type;
  1010. $channelName = $userBook['channel_name'];
  1011. //获取男频女频的标签文案
  1012. $womanPromotion = PromotionService::getRandomHeadline(2, 1);
  1013. $manPromotion = PromotionService::getRandomHeadline(1, 1);
  1014. if ($channelName == '男频') {
  1015. $book['title'] = $manPromotion[0]['title'];
  1016. $book['description'] = $manPromotion[0]['title'];
  1017. } else {
  1018. $book['title'] = $womanPromotion[0]['title'];
  1019. $book['description'] = $womanPromotion[0]['title'];
  1020. }
  1021. //头条的图片从财哥个图库中随机取一张
  1022. $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
  1023. if ($promotionImages) {
  1024. $book['image'] = $promotionImages[0]['link'];
  1025. } else {
  1026. $book['image'] = $userBook['cover'];
  1027. }
  1028. $booksArray = [['title' => $book['title']], ['description' => $book['description']], ['url' => $book['url']], ['image' => $book['image']]];
  1029. }
  1030. return $booksArray;
  1031. }
  1032. /**
  1033. * 得到指定书籍的所有信息
  1034. */
  1035. static function get_book_full_infos($books, $category_type = '')
  1036. {
  1037. $booksArray = [];
  1038. //5,获取男频女频的标签文案
  1039. $womanPromotion = PromotionService::getRandomHeadline(2, count($books));
  1040. $manPromotion = PromotionService::getRandomHeadline(1, count($books));
  1041. $promotionNum = 0;
  1042. if ($books) {
  1043. foreach ($books as $key => $value) {
  1044. $channelName = $value->channel_name;
  1045. $cover = $value->cover;
  1046. if ($channelName == '男频') {
  1047. $book['title'] = $manPromotion[$promotionNum]['title'];
  1048. $book['description'] = $manPromotion[$promotionNum]['title'];
  1049. } else {
  1050. $book['title'] = $womanPromotion[$promotionNum]['title'];
  1051. $book['description'] = $womanPromotion[$promotionNum]['title'];
  1052. }
  1053. //通过判断书籍是男频还是女频拼接书籍信息的不同标签文案
  1054. // if(strpos($bookUrl.$value->url,'?') > -1){
  1055. // $urlBook = $value->url = $bookUrl.$value->url.'&fromtype='.$category_type.'&source=wechatmsg';
  1056. // }else{
  1057. // $urlBook = $value->url = $bookUrl.$value->url.'?fromtype='.$category_type.'&source=wechatmsg';
  1058. // }
  1059. $book['url'] = $value->url;
  1060. // $book['image'] = $cover;
  1061. if ($promotionNum == 0) {
  1062. //第一条图片选用图库中的图片地址
  1063. $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
  1064. if ($promotionImages) {
  1065. $book['image'] = $promotionImages[0]['link'];
  1066. } else {
  1067. $book['image'] = $cover;
  1068. }
  1069. } else {
  1070. $book['image'] = $cover;
  1071. }
  1072. $booksArray[$key] = [['title' => $book['title']], ['description' => $book['description']], ['url' => $book['url']], ['image' => $book['image']]];
  1073. $promotionNum++;
  1074. }
  1075. }
  1076. return $booksArray;
  1077. }
  1078. //-------------------------------------------------客服消息配置开关Start---------------------------CustomMsgSwitchs
  1079. /**
  1080. * 开启或关闭客服消息
  1081. */
  1082. static function customMsgSwitchSetting($distribution_channel_id, $custom_category, $status, $is_self_content = 0)
  1083. {
  1084. try {
  1085. //获取分销渠道下指定的一个智能推送
  1086. $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id, $custom_category);
  1087. if (!empty($customMsgSwitch)) {
  1088. //设置推送状态 1,开启 2,关闭
  1089. $customMsgSwitch['status'] = $status;
  1090. $customMsgSwitch['is_self_content'] = $is_self_content;
  1091. $customMsgSwitch->save();
  1092. return 1;
  1093. } else {
  1094. return 0;
  1095. }
  1096. } catch (\Exception $e) {
  1097. return 2;
  1098. }
  1099. }
  1100. /**
  1101. * 根据distribution_channel_id获取客服消息开关
  1102. */
  1103. static function customMsgSwitchsByChannelId($distribution_channel_id)
  1104. {
  1105. \Log::info('customMsgSwitchsByChannelId_start:' . $distribution_channel_id);
  1106. $result = array();
  1107. // 渠道个性配置
  1108. $custom_msg_switch_infos = self::GetCustomMsgSwitchsByChannelId($distribution_channel_id);
  1109. // 基础素材配置
  1110. $customMsgSwitchs = CustomMsgSwitchs::getCustomMsgSwitchByCategorys();
  1111. \Log::info('$custom_msg_switch_infos');
  1112. \Log::info($custom_msg_switch_infos);
  1113. \Log::info('$customMsgSwitchs');
  1114. \Log::info($customMsgSwitchs);
  1115. // 组装素材,全部后台配置
  1116. foreach ($custom_msg_switch_infos as $key => $custom_msg_switch_info) {
  1117. // \Log::info($custom_msg_switch_info);
  1118. $customMsgSwitch = $customMsgSwitchs[$custom_msg_switch_info->custom_category];
  1119. // 不展示
  1120. if ($customMsgSwitch['status'] == 0) {
  1121. continue;
  1122. }
  1123. $result[$key]['status'] = $custom_msg_switch_info->status;
  1124. $result[$key]['id'] = $custom_msg_switch_info->id;
  1125. $result[$key]['custom_category'] = $custom_msg_switch_info->custom_category;
  1126. $result[$key]['distribution_channel_id'] = $custom_msg_switch_info->distribution_channel_id;
  1127. $result[$key]['title'] = $customMsgSwitch['title'];
  1128. $result[$key]['desc_content'] = $customMsgSwitch['desc_content'];
  1129. $result[$key]['img_url'] = $customMsgSwitch['img_url'];
  1130. $result[$key]['common_is_self_content'] = $customMsgSwitch['is_self_content'];
  1131. $result[$key]['is_self_content'] = $custom_msg_switch_info->is_self_content;
  1132. }
  1133. return $result;
  1134. }
  1135. /**
  1136. * 根据distribution_channel_id获取客服消息开关
  1137. */
  1138. static function GetCustomMsgSwitchsByChannelId($distribution_channel_id)
  1139. {
  1140. //1,首先尝试获取该渠道下的智能推送开关
  1141. $customMsgSwitchsMsgs = CustomMsgSwitchsMsgs::customMsgSwitchsMsgsByChannelId($distribution_channel_id);
  1142. if (count($customMsgSwitchsMsgs) > 0) {
  1143. //2,该渠道下有智能推送的配置信息,开始对比过滤
  1144. $customMsgSwitchsMsgsArray = [];
  1145. //3,获取智能推送基础配置表的推送开关信息
  1146. $customMsgSwitchs = CustomMsgSwitchs::customMsgSwitchs();
  1147. //4,判断如果渠道下的只能推送开关数量和基础配置下的相同,则直接返回查到的所有客服开关
  1148. if (count($customMsgSwitchsMsgs) == count($customMsgSwitchs)) {
  1149. return $customMsgSwitchsMsgs;
  1150. } else {
  1151. //5,如果数量不一致,则渠道下需要更新智能开关的数量,与配置表保持一致,少补,多的保留
  1152. //先循环渠道下所有的只能客服推送数量,通过custom_category关联基础配置表,
  1153. //如果渠道下所查询到的custom_category在基础表中不存在,则说明该智能客服推送配置已删除,渠道下也要删除多余的配置项
  1154. for ($i = 0; $i < count($customMsgSwitchsMsgs); $i++) {
  1155. $customMsgSwitchsSerch = CustomMsgSwitchs::customMsgSwitchsBySwitchId($customMsgSwitchsMsgs[$i]['custom_category']);
  1156. // 有些是需要特殊开着的,多的留着
  1157. if (empty($customMsgSwitchsSerch)) {
  1158. // $customMsgSwitchsMsgs[$i]->delete();
  1159. } else {
  1160. $customMsgSwitchsMsgsArray[] = $customMsgSwitchsMsgs[$i];
  1161. }
  1162. }
  1163. //再循环基础配置表获取custom_category,看在渠道的智能客服推送配置中是否存在,
  1164. //如果不存在,则说明这是最新配置的智能客服推送项,该渠道需要新增一条默认为关闭的智能推送开关
  1165. for ($i = 0; $i < count($customMsgSwitchs); $i++) {
  1166. $customMsgSwitchsMsg = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id, $customMsgSwitchs[$i]['custom_category']);
  1167. if (empty($customMsgSwitchsMsg)) {
  1168. # code...
  1169. $customMsg['custom_category'] = $customMsgSwitchs[$i]['custom_category'];
  1170. if ($customMsg['custom_category'] == 'auto_custom_trusteeship') {
  1171. $customMsg['status'] = '2';// 客服消息托管
  1172. } else {
  1173. $customMsg['status'] = '1';// 默认开
  1174. }
  1175. $customMsg['distribution_channel_id'] = $distribution_channel_id;
  1176. $customMsgSwitchsMsgNew = CustomMsgSwitchsMsgs::create($customMsg);
  1177. $customMsgSwitchsMsgsArray[] = $customMsgSwitchsMsgNew;
  1178. }
  1179. }
  1180. //6,同步完成后,返回正确的客服推送信息
  1181. return $customMsgSwitchsMsgsArray;
  1182. }
  1183. } else {
  1184. //7,如果该渠道没有智能开关配置,则说明该渠道是新增的渠道,
  1185. //通过基础配置表为该渠道创建相应的智能客服推送,默认关闭
  1186. $customMsgSwitchsMsgsArray = [];
  1187. $customMsgSwitchs = CustomMsgSwitchs::customMsgSwitchs();
  1188. if (count($customMsgSwitchs) > 0) {
  1189. for ($i = 0; $i < count($customMsgSwitchs); $i++) {
  1190. $customMsgSwitchsMsg['custom_category'] = $customMsgSwitchs[$i]['custom_category'];
  1191. if ($customMsgSwitchsMsg['custom_category'] == 'auto_custom_trusteeship') {
  1192. $customMsgSwitchsMsg['status'] = '2';// 客服消息托管
  1193. } else {
  1194. $customMsgSwitchsMsg['status'] = '1';// 默认开
  1195. }
  1196. $customMsgSwitchsMsg['distribution_channel_id'] = $distribution_channel_id;
  1197. $customMsgSwitchsMsgNew = CustomMsgSwitchsMsgs::create($customMsgSwitchsMsg);
  1198. $customMsgSwitchsMsgsArray[] = $customMsgSwitchsMsgNew;
  1199. }
  1200. }
  1201. return $customMsgSwitchsMsgsArray;
  1202. }
  1203. }
  1204. /**
  1205. * 获取指定客服消息开关
  1206. */
  1207. static function customMsgSwitchsByChannelCate($distribution_channel_id, $custom_category)
  1208. {
  1209. return CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id, $custom_category);
  1210. }
  1211. //-------------------------------------------------客服消息配置开关End---------------------------CustomMsgSwitchs
  1212. //-------------------------------------------------编辑发送客服消息Start---------------------------CustomSendMsg
  1213. /**
  1214. * 根据distribution_channel_id获取发送客服消息列表
  1215. */
  1216. static function customSendMsgsByChannelId($distribution_channel_id)
  1217. {
  1218. return CustomSendMsgs::customSendMsgsByChannelId($distribution_channel_id);
  1219. }
  1220. /**
  1221. * 搜索
  1222. */
  1223. static function searchCustomSendMsgs($param, $is_all = false)
  1224. {
  1225. return CustomSendMsgs::searchCustomSendMsgs($param, $is_all);
  1226. }
  1227. /**
  1228. * 根据distribution_channel_id和托管信息获取发送客服消息列表
  1229. */
  1230. static function customSendMsgsByChannelIdAndTrusteeship($customerPrams)
  1231. {
  1232. return CustomSendMsgs::customSendMsgsByChannelIdAndTrusteeship($customerPrams['distribution_channel_id'], $customerPrams['trusteeship']);
  1233. }
  1234. /**
  1235. * 根据托管信息获取发送客服消息列表
  1236. */
  1237. static function customSendMsgsByTrusteeship($customerPrams)
  1238. {
  1239. return CustomSendMsgs::customSendMsgsByTrusteeship($customerPrams['trusteeship']);
  1240. }
  1241. /**
  1242. * 托管信息信息
  1243. * @param $day
  1244. * @return mixed
  1245. */
  1246. public static function customSendMsgsByTrusteeshipGroup($day)
  1247. {
  1248. return CustomSendMsgs::where('trusteeship', 1)
  1249. ->where('del_flag', 0)
  1250. ->where('send_time', '>=', $day)
  1251. ->where('send_time', '<=', $day . ' 23:59:59')
  1252. ->groupBy('distribution_channel_id')
  1253. ->select('distribution_channel_id', DB::raw('GROUP_CONCAT(id) as ids'), DB::raw('sum(user_num) as user_num'))
  1254. ->get();
  1255. }
  1256. /**
  1257. * 托管信息信息
  1258. * @param $day
  1259. * @return mixed
  1260. */
  1261. public static function customSendMsgsByTrusteeshipByChannelId($distribution_channel_id, $date)
  1262. {
  1263. return CustomSendMsgs::where('trusteeship', 1)
  1264. ->where('del_flag', 0)
  1265. ->where('distribution_channel_id', '=', $distribution_channel_id)
  1266. ->where('send_time', '>=', $date)
  1267. ->groupBy('distribution_channel_id')
  1268. ->select(DB::raw('GROUP_CONCAT(id) as ids'), DB::raw('sum(user_num) as user_num'))
  1269. ->first();
  1270. }
  1271. /**
  1272. * 根据托管信息获取发送客服消息列表
  1273. */
  1274. static function customSendMsgsByTrusteeshipAndBacthNo($customerPrams)
  1275. {
  1276. return CustomSendMsgs::customSendMsgsByTrusteeshipAndBacthNo($customerPrams['trusteeship'], $customerPrams['batch_no']);
  1277. }
  1278. //判断1小时内是否有相同的客服消息插入过
  1279. static function isSendCustomerAtSameTime($customerPrams)
  1280. {
  1281. return CustomSendMsgs::isSendCustomerAtSameTime($customerPrams['distribution_channel_id'], $customerPrams['appid'], $customerPrams['send_time']);
  1282. }
  1283. //判断1小时内是否有相同的客服消息插入过
  1284. static function isSendCustomerAtSameTimeAndSex($customerPrams)
  1285. {
  1286. return CustomSendMsgs::isSendCustomerAtSameTimeAndSex($customerPrams['distribution_channel_id'], $customerPrams['appid'], $customerPrams['send_time'], $customerPrams['sex']);
  1287. }
  1288. /**
  1289. * 根据task_id获取发送客服消息
  1290. */
  1291. static function customSendMsgsByTaskid($task_id)
  1292. {
  1293. return CustomSendMsgs::customSendMsgsByTaskid($task_id);
  1294. }
  1295. /**
  1296. * 根据id获取发送客服消息
  1297. */
  1298. static function customSendMsgsById($id)
  1299. {
  1300. return CustomSendMsgs::customSendMsgsById($id);
  1301. }
  1302. /**
  1303. * 停止客服消息发送
  1304. */
  1305. static function updateCustomSendMsgsStatus($id)
  1306. {
  1307. try {
  1308. $customSendMsgs = CustomSendMsgs::customSendMsgsById($id);
  1309. if (!empty($customSendMsgs)) {
  1310. if ($customSendMsgs['status'] == '8') {
  1311. \Log::info('该客服已经在发送状态,不允许编辑' . $customSendMsgs['task_id']);
  1312. return 4;
  1313. }
  1314. $customSendMsgs['status'] = '4';
  1315. $customSendMsgs->save();
  1316. $officialAccountArray = $customSendMsgs->toArray();
  1317. Redis::hset('send_wechat_msg:task_id:' . $customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));
  1318. return 1;
  1319. } else {
  1320. return 2;
  1321. }
  1322. } catch (\Exception $e) {
  1323. \Log::info('updateCustomSendMsgsStatus_ept:' . $e->getMessage());
  1324. return 0;
  1325. }
  1326. }
  1327. /**
  1328. * 更新客服消息发送,兼容删除
  1329. */
  1330. static function updateCustomSendMsgsStatusMulty($id, $status, $del_flag = 0)
  1331. {
  1332. try {
  1333. $customSendMsgs = CustomSendMsgs::customSendMsgsById($id);
  1334. if (!empty($customSendMsgs)) {
  1335. // 由于批次状态暂时不更新,所以子渠道强制更新状态
  1336. // if($customSendMsgs['status'] == '8'){
  1337. // \Log::info('updateCustomSendMsgsStatusMulty,status=8:'.$customSendMsgs['task_id']);
  1338. // return 4;
  1339. // }
  1340. $customSendMsgs['status'] = $status;
  1341. $customSendMsgs['del_flag'] = $del_flag;
  1342. $customSendMsgs->save();
  1343. $officialAccountArray = $customSendMsgs->toArray();
  1344. Redis::hset('send_wechat_msg:task_id:' . $customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));
  1345. return 1;
  1346. } else {
  1347. return 2;
  1348. }
  1349. } catch (\Exception $e) {
  1350. \Log::info('updateCustomSendMsgsStatusMulty_ept:' . $e->getMessage());
  1351. return 0;
  1352. }
  1353. }
  1354. /**
  1355. * 发送客服消息
  1356. */
  1357. static function addCustomSendMsgs($customSendMsgsPrams)
  1358. {
  1359. try {
  1360. $appids = $customSendMsgsPrams['appid'];
  1361. $appidArray = explode(',', $appids);
  1362. $usercountnum = 0;
  1363. $customSendMsgsPrams['task_id'] = 'custom_#' . $customSendMsgsPrams['distribution_channel_id'] . '#' . md5(uniqid());
  1364. //4,先在数据库创建一条新的客服消息
  1365. $customSendMsgsPrams['user_num'] = 0;
  1366. $customSendMsgsPrams['del_flag'] = 0;
  1367. $customSendMsgs = CustomSendMsgs::create($customSendMsgsPrams);
  1368. $customSendMsgsPrams['id'] = $customSendMsgs['id'];
  1369. $officialAccountArray = $customSendMsgs->toArray();
  1370. Redis::hset('send_wechat_msg:task_id:' . $customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));
  1371. return 1;
  1372. } catch (\Exception $e) {
  1373. \Log::info('===================================发送客服消息报错');
  1374. \Log::info($e->getMessage());
  1375. return 0;
  1376. }
  1377. }
  1378. /**
  1379. * 修改客服消息
  1380. */
  1381. static function editCustomSendMsgs($customSendMsgsPrams)
  1382. {
  1383. try {
  1384. $customSendMsgs = CustomSendMsgs::customSendMsgsById($customSendMsgsPrams['id']);
  1385. if ($customSendMsgs) {
  1386. if ($customSendMsgs['status'] == '8') {
  1387. \Log::info('该客服已经在发送状态,不允许编辑' . $customSendMsgs['task_id']);
  1388. return 4;
  1389. }
  1390. //1,先把原来的客服消息停止并删除
  1391. $customSendMsgs['status'] = '4';
  1392. $customSendMsgs['del_flag'] = 1;
  1393. $customSendMsgs->save();
  1394. $officialAccountArray = $customSendMsgs->toArray();
  1395. Redis::hset('send_wechat_msg:task_id:' . $customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));
  1396. // Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', '[{user_num:'.$customSendMsgs['user_num'].'},{appid:'.$customSendMsgs['appid'].'},{name:'.$customSendMsgs['name'].'},{send_time:'.$customSendMsgs['send_time'].'},{content:'.$customSendMsgs['content'].'},{redirect_url:'.$customSendMsgs['redirect_url'].'},{distribution_channel_id:'.$customSendMsgs['distribution_channel_id'].'},{subscribe_time:'.$customSendMsgs['subscribe_time'].'},{sex:'.$customSendMsgs['sex'].'},{balance:'.$customSendMsgs['balance'].'},{order_type:'.$customSendMsgs['order_type'].'},{category_id:'.$customSendMsgs['category_id'].'}]');
  1397. $isSendCustomer = self::isSendCustomerAtSameTime($customSendMsgsPrams);
  1398. if (!empty($isSendCustomer)) {
  1399. \Log::info('已经发送过该客服消息');
  1400. \Log::info($isSendCustomer['id']);
  1401. \Log::info($isSendCustomer['status']);
  1402. \Log::info($isSendCustomer['del_flag']);
  1403. return 3;
  1404. }
  1405. //2,创建一条新的模板消息
  1406. $appids = $customSendMsgsPrams['appid'];
  1407. $appidArray = explode(',', $appids);
  1408. $usercountnum = 0;
  1409. $customSendMsgsPrams['task_id'] = 'custom_#' . $customSendMsgsPrams['distribution_channel_id'] . '#' . md5(uniqid());
  1410. //4,先在数据库创建一条新的客服消息
  1411. $customSendMsgsPrams['user_num'] = 0;
  1412. $customSendMsgsPrams['del_flag'] = 0;
  1413. $customSendMsgs = CustomSendMsgs::create($customSendMsgsPrams);
  1414. $customSendMsgsPrams['id'] = $customSendMsgs['id'];
  1415. $officialAccountArray = $customSendMsgs->toArray();
  1416. Redis::hset('send_wechat_msg:task_id:' . $customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));
  1417. return 1;
  1418. } else {
  1419. return 2;
  1420. }
  1421. } catch (\Exception $e) {
  1422. \Log::info('===================================发送客服消息报错');
  1423. \Log::info($e->getMessage());
  1424. return 0;
  1425. }
  1426. }
  1427. /**
  1428. * 删除客服消息
  1429. */
  1430. static function delCustomSendMsgs($customSendMsgsPrams)
  1431. {
  1432. try {
  1433. $customSendMsgs = CustomSendMsgs::customSendMsgsById($customSendMsgsPrams['id']);
  1434. if ($customSendMsgs) {
  1435. if ($customSendMsgs['status'] == '8') {
  1436. \Log::info('该客服已经在发送状态,不允许编辑' . $customSendMsgs['task_id']);
  1437. return 4;
  1438. }
  1439. //1,先把原来的客服消息停止并删除
  1440. $customSendMsgs['status'] = '4';
  1441. $customSendMsgs['del_flag'] = 1;
  1442. $customSendMsgs->save();
  1443. $officialAccountArray = $customSendMsgs->toArray();
  1444. Redis::hset('send_wechat_msg:task_id:' . $customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));
  1445. return 1;
  1446. } else {
  1447. return 2;
  1448. }
  1449. } catch (\Exception $e) {
  1450. \Log::info('===================================发送客服消息报错');
  1451. \Log::info($e->getMessage());
  1452. return 0;
  1453. }
  1454. }
  1455. /**
  1456. * 测试发送客服消息
  1457. */
  1458. static function testAddCustomSendMsgs($customSendMsgsPrams)
  1459. {
  1460. try {
  1461. // 测试链接加上域名
  1462. $customSendMsgsPrams['content'] = TemplateCustomSendService::convert_custom_content($customSendMsgsPrams['content'], 'test', $customSendMsgsPrams['distribution_channel_id'], 0);
  1463. $appids = $customSendMsgsPrams['appid'];
  1464. $appidArray = explode(',', $appids);
  1465. for ($j = 0; $j < count($appidArray); $j++) {
  1466. \Log::info('testAddCustomSendMsgs_appid:' . $appidArray[$j]);
  1467. //1,获取指定的用户
  1468. $forceSubscribeUserPram['uid'] = $customSendMsgsPrams['uid'];
  1469. $forceSubscribeUserPram['appid'] = $appidArray[$j];
  1470. $forceSubscribeUserPram['distribution_channel_id'] = $customSendMsgsPrams['distribution_channel_id'];
  1471. $force_user = array();
  1472. $temp_force_user = ForceSubscribeService::forceSubscribeUsersByUidAndAppidAndChannelId($forceSubscribeUserPram);
  1473. \Log::info('temp_force_user');
  1474. \Log::info($temp_force_user);
  1475. if (count($temp_force_user) == 0) {
  1476. \Log::info('testAddCustomSendMsgs_has_no_user:' . $customSendMsgsPrams['uid']);
  1477. $direct_user = array('openid' => $customSendMsgsPrams['uid']);
  1478. $force_user[] = $direct_user;
  1479. } else {
  1480. $force_user = $temp_force_user;
  1481. }
  1482. \Log::info('force_user');
  1483. \Log::info($force_user);
  1484. if (count($force_user) > 0) {
  1485. for ($i = 0; $i < count($force_user); $i++) {
  1486. //2,测试循环用户发送客服消息
  1487. $data = array();
  1488. $data['openid'] = $force_user[$i]['openid'];
  1489. $data['appid'] = $appidArray[$j];
  1490. $data['news_content'] = $customSendMsgsPrams['content'];
  1491. $data['type'] = 'last_task';
  1492. $data['task_id'] = 'custom_f69556c4eb5274cefdb9ba0a477736366';
  1493. $data['send_time'] = date("Y-m-d H:i:s");
  1494. $send_data = array(
  1495. 'send_time' => date("Y-m-d H:i:s"),
  1496. 'data' => $data
  1497. );
  1498. $delay = 0;
  1499. // \Log::info('客服消息找到用户并发送===================================');
  1500. \Log::info('test_custom_msg_send:' . $data['openid']);
  1501. // \Log::info($data['appid']);
  1502. \Log::info($data['news_content']);
  1503. $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
  1504. dispatch($job);
  1505. }
  1506. }
  1507. }
  1508. return 1;
  1509. } catch (\Exception $e) {
  1510. \Log::info('===================================');
  1511. \Log::info($e->getMessage());
  1512. return 0;
  1513. }
  1514. }
  1515. //-------------------------------------------------编辑发送客服消息End---------------------------CustomSendMsg
  1516. //-------------------------------------------------生成图文链接Start---------------------------
  1517. public static function multi_upload_material_imgs($appId, $images, $imageType = 'common')
  1518. {
  1519. \Log::info('multi_upload_material_imgs [start]');
  1520. $client = new Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
  1521. $error = [];
  1522. $promises = [];
  1523. foreach ($images as $key => $imageUrl) {
  1524. $param = [
  1525. 'gzh_app_id' => $appId,
  1526. 'img_url' => $imageUrl,
  1527. 'image_type' => $imageType,
  1528. 'group_nick' => env('GROUP_NICK'),
  1529. 'timestamp' => time()
  1530. ];
  1531. $param['sign'] = get_sign($param);
  1532. $uri = 'upload_material_img?' . http_build_query($param);
  1533. $promises[$key] = $client->getAsync($uri);
  1534. }
  1535. $results = Promise\unwrap($promises);
  1536. $urls = [];
  1537. foreach ($images as $key => $imageUrl) {
  1538. $res = $results[$key]->getBody()->getContents();
  1539. $res = json_decode($res, true);
  1540. if ($res['code']) {
  1541. $urls[$key] = [
  1542. 'old_url' => $imageUrl,
  1543. 'new_url' => getProp($res['data'], 'url'),
  1544. 'media_id' => getProp($res['data'], 'media_id'),
  1545. ];
  1546. } else {
  1547. $error[$imageType] = $res['msg'];
  1548. }
  1549. }
  1550. \Log::info('multi_upload_material_imgs urls: ' . $imageType);
  1551. \Log::info($urls);
  1552. \Log::info($error);
  1553. return compact('urls', 'error');
  1554. }
  1555. /**
  1556. * 上传微信图片
  1557. * @param unknown_type $gzh_app_id
  1558. * @param unknown_type $img_url
  1559. * @param unknown_type $group_nick
  1560. * @param unknown_type $timestamp
  1561. */
  1562. static function upload_material_img($param)
  1563. {
  1564. $params = array("gzh_app_id" => $param['gzh_app_id'], "img_url" => $param['img_url'], "group_nick" => $param['group_nick'], "timestamp" => $param['timestamp']);
  1565. $sign = get_sign($params);
  1566. //获取封面图片media_id
  1567. $mediaCustomerJson = self::getUserClient()->request("GET", "upload_material_img/",
  1568. ['query' => ['gzh_app_id' => $param['gzh_app_id'], 'img_url' => $param['img_url'], 'group_nick' => $param['group_nick'], 'timestamp' => $param['timestamp'], 'sign' => $sign], 'connect_timeout' => 3]
  1569. )->getBody()->getContents();
  1570. \Log::info("alter_upload_material_img:" . $param['gzh_app_id'] . ' img_url:' . $param['img_url']);
  1571. \Log::info($mediaCustomerJson);
  1572. $mediaCustomerArray = json_decode($mediaCustomerJson, true);
  1573. return $mediaCustomerArray;
  1574. }
  1575. /**
  1576. * 上传微信图片
  1577. * @param unknown_type $gzh_app_id
  1578. * @param unknown_type $img_url
  1579. * @param unknown_type $group_nick
  1580. * @param unknown_type $timestamp
  1581. */
  1582. static function upload_material_img_by_type($param)
  1583. {
  1584. $params = array("gzh_app_id" => $param['gzh_app_id'], 'image_type' => $param['image_type'], "img_url" => $param['img_url'], "group_nick" => $param['group_nick'], "timestamp" => $param['timestamp']);
  1585. $sign = get_sign($params);
  1586. //获取封面图片media_id
  1587. $mediaCustomerJson = self::getUserClient()->request("GET", "upload_material_img/",
  1588. ['query' => ['gzh_app_id' => $param['gzh_app_id'], 'image_type' => $param['image_type'], 'img_url' => $param['img_url'], 'group_nick' => $param['group_nick'], 'timestamp' => $param['timestamp'], 'sign' => $sign], 'connect_timeout' => 3]
  1589. )->getBody()->getContents();
  1590. \Log::info("alter_upload_material_img_by_type_img:" . $param['gzh_app_id'] . ' img_url:' . $param['img_url']);
  1591. \Log::info($mediaCustomerJson);
  1592. $mediaCustomerArray = json_decode($mediaCustomerJson, true);
  1593. return $mediaCustomerArray;
  1594. }
  1595. public static function multy_upload_material_imgs($content, $last_urls, $base_param)
  1596. {
  1597. \Log::info('multy_upload_material_imgs_start');
  1598. \Log::info('last_urls');
  1599. \Log::info($last_urls);
  1600. $multy_urls = [];
  1601. foreach ($last_urls as $last_url) {
  1602. if (strpos($last_url, 'mmbiz.qpic.cn') > -1) {
  1603. \Log::info('wx_url_continue:' . $last_url);
  1604. continue;
  1605. }
  1606. $last_url = str_replace(array("&amp;", "&quot;", "amp;", "quot;"), "", htmlspecialchars($last_url));
  1607. $params = array("gzh_app_id" => $base_param['gzh_app_id'], "img_url" => $last_url, "group_nick" => $base_param['group_nick'], "timestamp" => $base_param['timestamp']);
  1608. $sign = get_sign($params);
  1609. $params['sign'] = $sign;
  1610. $url = env('MEDIA_API_BASE_URI') . 'upload_material_img?' . http_build_query($params);
  1611. $multy_url = [];
  1612. $multy_url['request_url'] = $url;
  1613. $multy_url['old_url'] = $last_url;
  1614. $multy_urls[] = $multy_url;
  1615. }
  1616. // 最多尝试3次
  1617. $try_time = 0;
  1618. while ($try_time < 3) {
  1619. try {
  1620. $url_mappings = self::multiRequest($multy_urls);
  1621. \Log::info('$url_mappings');
  1622. \Log::info($url_mappings);
  1623. if (!empty($url_mappings)) {
  1624. \Log::info('multiRequest_success');
  1625. break;
  1626. }
  1627. } catch (\Exception $e) {
  1628. \Log::info('multiRequest_ept:' . $e->getMessage());
  1629. }
  1630. $try_time++;
  1631. }
  1632. if ($try_time == 3) {
  1633. \Log::info('multiRequest_error_return:');
  1634. return '';
  1635. }
  1636. foreach ($url_mappings as $key => $url_mapping) {
  1637. \Log::info('replace_old_url:' . $url_mapping['old_url'] . ' new_url:' . $url_mapping['new_url']);
  1638. $content = str_replace($url_mapping['old_url'], $url_mapping['new_url'], $content);
  1639. }
  1640. return $content;
  1641. }
  1642. static function multiRequest($data)
  1643. {
  1644. $client = new Client(
  1645. ['allow_redirects' => true,
  1646. 'timeout' => 120000]);
  1647. $promises = [];
  1648. $mappings = [];
  1649. for ($i = 0; $i < count($data); $i++) {
  1650. \Log::info('async_url:' . $data[$i]['request_url']);
  1651. $promises[$i] = $client->getAsync($data[$i]['request_url']);
  1652. }
  1653. $results = Promise\unwrap($promises);
  1654. // \Log::info('multy_$results');\Log::info($results);
  1655. $j = 0;
  1656. foreach ($data as $key => &$v) {
  1657. $res = $results[$key]->getBody()->getContents();
  1658. $res = json_decode($res, true);
  1659. \Log::info('res:' . $key . ' res:' . json_encode($res));
  1660. $mappings[$key]['old_url'] = $data[$key]['old_url'];
  1661. if ($res['code'] == 1) {
  1662. $mappings[$key]['new_url'] = $res['data']['url'];
  1663. } else {
  1664. \Log::info('multiRequest_error_return:' . $data[$key]['old_url'] . ' res:' . json_encode($res) . ' request_url:' . $data[$key]['request_url']);
  1665. return null;
  1666. }
  1667. }
  1668. return $mappings;
  1669. }
  1670. // 单个链接上传替换
  1671. static function one_upload_material_imgs($content, $last_urls)
  1672. {
  1673. \Log::info('one_upload_material_imgs_start');
  1674. foreach ($last_urls as $key => $last_url) {
  1675. \Log::info('last_urls_count:' . count($last_urls) . ' now:' . $key);
  1676. if (strpos($last_url, 'mmbiz.qpic.cn') > -1) {
  1677. \Log::info('wx_url_continue:' . $last_url);
  1678. continue;
  1679. }
  1680. $last_url = str_replace(array("&amp;", "&quot;", "amp;", "quot;"), "", htmlspecialchars($last_url));
  1681. // TODO 加try 3次?
  1682. $i = 0;
  1683. while ($i < 3) {
  1684. try {
  1685. \Log::info('child_upload_material_img_start:i' . $i . ' last_url:' . $last_url);
  1686. $param['img_url'] = $last_url;
  1687. $upload_res = self::upload_material_img($param);
  1688. \Log::info('$upload_res');
  1689. \Log::info($upload_res);
  1690. if ($upload_res['code'] == 1) {
  1691. $content = str_replace($last_url, $upload_res['data']['url'], $content);
  1692. break;
  1693. }
  1694. } catch (\Exception $e) {
  1695. \Log::info('upload_matrial_img_ept:' . $e->getMessage());
  1696. sleep(1);
  1697. }
  1698. $i++;
  1699. }
  1700. if ($i == 3) {
  1701. \Log::info('upload_matrial_img_return');
  1702. return null;
  1703. }
  1704. }
  1705. return $content;
  1706. }
  1707. public static function extract_content_images($content)
  1708. {
  1709. // 获取url list
  1710. // 防封模式、第一条封面图要去掉
  1711. //<img src="http://yueduyun.oss-cn-hangzhou.aliyuncs.com/book_chapter_image_test/5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY/1/1_0.jpg"
  1712. preg_match_all('/<img src="(.*)"/U', $content, $ff_matchs);
  1713. $ff_urls = isset($ff_matchs[1]) ? $ff_matchs[1] : array();
  1714. // if (isset($ff_urls[0])) {
  1715. // unset($ff_urls[0]);
  1716. // }
  1717. \Log::info('ff_matchs:');
  1718. \Log::info($ff_urls);
  1719. // 背景图模式
  1720. //background: url(&quot;http://yueduyun.oss-cn-hangzhou.aliyuncs.com/book_chapter_image_test/5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY/1/1_0.jpg&quot;)
  1721. preg_match_all('/background: url\((.*)\)/U', $content, $bg_matchs);
  1722. $bg_urls = isset($bg_matchs[1]) ? $bg_matchs[1] : array();
  1723. \Log::info('bg_urls:');
  1724. \Log::info($bg_urls);
  1725. $last_urls = array_merge($ff_urls, $bg_urls);
  1726. \Log::info('$last_urls');
  1727. \Log::info($last_urls);
  1728. if ($last_urls) {
  1729. foreach ($last_urls as &$last_url) {
  1730. $last_url = str_replace(['&quot;', '&amp;'], '', $last_url);
  1731. }
  1732. }
  1733. return $last_urls;
  1734. }
  1735. public static function replace_content_images($materials, $images, $uploadImages)
  1736. {
  1737. foreach ($materials as &$material) {
  1738. $material['content'] = str_replace($images, $uploadImages, $material['content']);
  1739. }
  1740. return $materials;
  1741. }
  1742. /**
  1743. * @param $channelId
  1744. * @param $msgInfo
  1745. * @param $materials
  1746. * @param $upThumbsUrls
  1747. * @return array|bool|mixed
  1748. * @throws \GuzzleHttp\Exception\GuzzleException
  1749. */
  1750. public static function upload_articles($channelId, $msgInfo, $materials, $upThumbsUrls)
  1751. {
  1752. $articles = [];
  1753. foreach ($materials as $key => $material) {
  1754. $upThumbsUrlInfo = collect($upThumbsUrls)->where('old_url', getProp($material, 'cover_url'))->first();
  1755. $thumbMediaId = getProp($upThumbsUrlInfo, 'media_id');
  1756. // 原文链接
  1757. $materialId = getProp($material, 'id');
  1758. $url = BatchWechatCustomSendService::checkAddDomain($channelId, getProp($material, 'url'));
  1759. $sourceUrl = BatchWechatCustomSendService::redirect_url_add_param($url, $materialId, 'batch_custom');
  1760. $tmp = [
  1761. 'thumb_media_id' => $thumbMediaId,
  1762. 'author' => getProp($msgInfo, 'name'),
  1763. 'title' => getProp($material, 'title'),
  1764. 'content_source_url' => $sourceUrl,
  1765. 'content' => getProp($material, 'content'),
  1766. 'digest' => getProp($material, 'desc'),
  1767. 'show_cover_pic' => 0,
  1768. ];
  1769. $tmp['sign'] = get_sign($tmp);
  1770. $articles[] = $tmp;
  1771. }
  1772. if (empty($articles)) {
  1773. return false;
  1774. }
  1775. //获取图文素材链接
  1776. try {
  1777. $data = [
  1778. 'group_nick' => env('GROUP_NICK'),
  1779. 'gzh_app_id' => getProp($msgInfo, 'appid'),
  1780. 'articles' => json_encode($articles, JSON_UNESCAPED_UNICODE),
  1781. 'timestamp' => time()
  1782. ];
  1783. $data['sign'] = get_sign($data);
  1784. \Log::info("upload_gzh_articles request");
  1785. \Log::info($data);
  1786. $jsonStr = self::getUserClient()->request('POST', 'upload_gzh_articles/', [
  1787. 'form_params' => $data,
  1788. 'connect_timeout' => 10
  1789. ])->getBody()->getContents();
  1790. \Log::info("============================获取素材图文链接 通过接口整合获得 content_source_url");
  1791. \Log::info($jsonStr);
  1792. } catch (\Exception $e) {
  1793. \Log::info('createOfficialImgTxtUrl_ept:' . $e->getMessage());
  1794. return [];
  1795. }
  1796. return json_decode($jsonStr, true);
  1797. }
  1798. /**
  1799. * 转化章节图片为微信的url
  1800. * @param $content
  1801. * @param $param
  1802. * @return mixed|string
  1803. */
  1804. static function convert_content_wechat_url($content, $param)
  1805. {
  1806. \Log::info('convert_content_wechat_url_start:' . json_encode($param));
  1807. // 获取url list
  1808. // 防封模式、第一条封面图要去掉
  1809. //<img src="http://yueduyun.oss-cn-hangzhou.aliyuncs.com/book_chapter_image_test/5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY/1/1_0.jpg"
  1810. preg_match_all('/<img src="(.*)"/U', $content, $ff_matchs);
  1811. $ff_urls = isset($ff_matchs[1]) ? $ff_matchs[1] : array();
  1812. if (isset($ff_urls[0])) {
  1813. unset($ff_urls[0]);
  1814. }
  1815. \Log::info('ff_matchs:');
  1816. \Log::info($ff_urls);
  1817. // 背景图模式
  1818. //background: url(&quot;http://yueduyun.oss-cn-hangzhou.aliyuncs.com/book_chapter_image_test/5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY/1/1_0.jpg&quot;)
  1819. preg_match_all('/background: url\((.*)\)/U', $content, $bg_matchs);
  1820. $bg_urls = isset($bg_matchs[1]) ? $bg_matchs[1] : array();
  1821. \Log::info('bg_urls:');
  1822. \Log::info($bg_urls);
  1823. $last_urls = array_merge($ff_urls, $bg_urls);
  1824. \Log::info('$last_urls');
  1825. \Log::info($last_urls);
  1826. if (!empty($last_urls)) {
  1827. \Log::info('before_convert:');
  1828. \Log::info($content);
  1829. $content = self::multy_upload_material_imgs($content, $last_urls, $param);
  1830. \Log::info('after_convert:');
  1831. \Log::info($content);
  1832. }
  1833. return $content;
  1834. }
  1835. /**
  1836. * 生成图文链接
  1837. */
  1838. static function createOfficialImgTxtUrl($officialImgTxtUrlPrams)
  1839. {
  1840. $img_url = $officialImgTxtUrlPrams['img_url'];
  1841. $content = $officialImgTxtUrlPrams['content'];
  1842. $title = $officialImgTxtUrlPrams['title'];
  1843. $distribution_channel_id = $officialImgTxtUrlPrams['distribution_channel_id'];
  1844. $book_name = $officialImgTxtUrlPrams['book_name'];
  1845. $chapter_sequence = $officialImgTxtUrlPrams['chapter_sequence'];
  1846. $send_orders_id = $officialImgTxtUrlPrams['send_orders_id'];
  1847. $send_orders_name = $officialImgTxtUrlPrams['send_orders_name'];
  1848. $send_orders_url = $officialImgTxtUrlPrams['send_orders_url'];
  1849. $show_cover_pic = 1;
  1850. $gzh_app_id = '';
  1851. $digest = '';
  1852. $author = '';
  1853. $thumb_media_id = '';
  1854. $officialAccountprams['distribution_channel_id'] = $distribution_channel_id;
  1855. $officialAccounts = OfficialAccountService::officialAuthAccountBydistributionChannelId($officialAccountprams);
  1856. if (count($officialAccounts) > 0) {
  1857. $gzh_app_id = $officialAccounts[0]['appid'];
  1858. // $gzh_app_id = 'wxb2aaa55b088f12e9';
  1859. $timestamp = (time());
  1860. $group_nick = env('GROUP_NICK');
  1861. $param = [
  1862. 'timestamp' => $timestamp,
  1863. 'group_nick' => $group_nick,
  1864. 'gzh_app_id' => $gzh_app_id,
  1865. 'img_url' => $img_url
  1866. ];
  1867. // 内容的链接转化为微信的官方链接,否则文章上传会被过滤掉
  1868. $content = self::convert_content_wechat_url($content, $param);
  1869. // 转化异常直接返回
  1870. if (empty($content)) {
  1871. return '';
  1872. }
  1873. try {
  1874. $mediaCustomerArray = self::upload_material_img($param);
  1875. if ($mediaCustomerArray['code'] == 1) {
  1876. $mediaCustomerData = $mediaCustomerArray['data'];
  1877. if (!empty($mediaCustomerData)) {
  1878. $thumb_media_id = $mediaCustomerData['media_id'];
  1879. $param2s = array("show_cover_pic" => $show_cover_pic, "author" => $author, "digest" => $digest, "content" => $content, "title" => $title, "thumb_media_id" => $thumb_media_id, "gzh_app_id" => $gzh_app_id, "group_nick" => $group_nick, "timestamp" => $timestamp);
  1880. $sign2 = get_sign($param2s);
  1881. \Log::info("============================开始请求创建素材URL接口");
  1882. //获取图文素材链接
  1883. $officialImgTxtUrlJson = self::getUserClient()->request("POST", "upload_gzh_article/",
  1884. ['form_params' => ["show_cover_pic" => $show_cover_pic, "author" => $author, "digest" => $digest, "content" => $content, "title" => $title, "thumb_media_id" => $thumb_media_id, "gzh_app_id" => $gzh_app_id, 'group_nick' => env('GROUP_NICK'), 'timestamp' => $timestamp, 'sign' => $sign2], 'connect_timeout' => 3]
  1885. )->getBody()->getContents();
  1886. \Log::info("============================获取素材图文链接 通过接口整合获得 content_source_url");
  1887. \Log::info($officialImgTxtUrlJson);
  1888. $officialImgTxtUrlArray = json_decode($officialImgTxtUrlJson, true);
  1889. if ($officialImgTxtUrlArray['code'] == 1) {
  1890. $officialImgTxtUrlData = $officialImgTxtUrlArray['data'];
  1891. if (!empty($officialImgTxtUrlData)) {
  1892. $content_source_url = $officialImgTxtUrlData['chapter_url'];
  1893. $officialImgTxtUrls['img_url'] = $img_url;
  1894. $officialImgTxtUrls['content'] = $content;
  1895. $officialImgTxtUrls['title'] = $title;
  1896. $officialImgTxtUrls['distribution_channel_id'] = $distribution_channel_id;
  1897. $officialImgTxtUrls['book_name'] = $book_name;
  1898. $officialImgTxtUrls['chapter_sequence'] = $chapter_sequence;
  1899. $officialImgTxtUrls['gzh_app_id'] = $gzh_app_id;
  1900. $officialImgTxtUrls['digest'] = $digest;
  1901. $officialImgTxtUrls['author'] = $author;
  1902. $officialImgTxtUrls['thumb_media_id'] = $thumb_media_id;
  1903. $officialImgTxtUrls['content_source_url'] = $content_source_url;
  1904. $officialImgTxtUrls['send_orders_id'] = $send_orders_id;
  1905. $officialImgTxtUrls['send_orders_name'] = $send_orders_name;
  1906. $officialImgTxtUrls['send_orders_url'] = $send_orders_url;
  1907. $officialImgTxtUrls['del_flag'] = 0;
  1908. OfficialImgtextUrls::create($officialImgTxtUrls);
  1909. return urldecode(str_replace("\/", "/", $content_source_url));
  1910. }
  1911. } else {
  1912. return '';
  1913. }
  1914. }
  1915. } else {
  1916. return '';
  1917. }
  1918. } catch (\Exception $e) {
  1919. \Log::info("createOfficialImgTxtUrl_ept:" . $e->getMessage());
  1920. return '';
  1921. }
  1922. }
  1923. }
  1924. /**
  1925. * 生成上传多个图文素材
  1926. */
  1927. static function createOfficialImgTxtUrls($officialImgTxtUrlPrams)
  1928. {
  1929. $distribution_channel_id = $officialImgTxtUrlPrams['distribution_channel_id'];
  1930. $appid = $officialImgTxtUrlPrams['appid'];
  1931. $articles = $officialImgTxtUrlPrams['articles'];
  1932. $show_cover_pic = 1;
  1933. $gzh_app_id = '';
  1934. $officialAccountprams['distribution_channel_id'] = $distribution_channel_id;
  1935. $officialAccounts = OfficialAccountService::officialAuthAccountBydistributionChannelId($officialAccountprams);
  1936. if (count($officialAccounts) > 0) {
  1937. $gzh_app_id = $appid;//$officialAccounts[0]['appid'];
  1938. // $gzh_app_id = 'wxb2aaa55b088f12e9';
  1939. $timestamp = (time());
  1940. $group_nick = env('GROUP_NICK');
  1941. $param = [
  1942. 'timestamp' => $timestamp,
  1943. 'group_nick' => $group_nick,
  1944. 'gzh_app_id' => $gzh_app_id,
  1945. ];
  1946. // 内容的链接转化为微信的官方链接,否则文章上传会被过滤掉
  1947. // $articles = self::convert_content_wechat_url($articles,$param);
  1948. // // 转化异常直接返回
  1949. // if(empty($articles)){
  1950. // \Log::info('convert_content_wechat_url_null_return');
  1951. // return '';
  1952. // }
  1953. try {
  1954. $form_params = array("articles" => json_encode($articles), "gzh_app_id" => $gzh_app_id, 'group_nick' => env('GROUP_NICK'), 'timestamp' => $timestamp);
  1955. $sign = get_sign($form_params);
  1956. $form_params['sign'] = $sign;
  1957. // $form_params['articles'] = $articles;
  1958. \Log::Info('$form_params');
  1959. \Log::info($form_params);
  1960. //获取图文素材链接
  1961. $officialImgTxtUrlJson = self::getUserClient()->request("POST", "upload_gzh_articles/",
  1962. ['form_params' => $form_params, 'connect_timeout' => 10]
  1963. )->getBody()->getContents();
  1964. \Log::info("============================获取多素材图文链接 通过接口整合获得 content_source_url");
  1965. \Log::info($officialImgTxtUrlJson);
  1966. $officialImgTxtUrlArray = json_decode($officialImgTxtUrlJson, true);
  1967. // return urldecode(str_replace("\/","/",$content_source_url));
  1968. return $officialImgTxtUrlArray;
  1969. } catch (\Exception $e) {
  1970. \Log::info("createOfficialImgTxtUrl_ept:" . $e->getMessage());
  1971. return '';
  1972. }
  1973. }
  1974. }
  1975. /**
  1976. * 获取图文列表
  1977. */
  1978. static function getOfficialImgTxtUrl($distribution_channel_id)
  1979. {
  1980. return OfficialImgtextUrls::officialImgtextUrlsByChannelId($distribution_channel_id);
  1981. }
  1982. /**
  1983. * 根据标题获取图文列表
  1984. */
  1985. static function getOfficialImgTxtUrlByBookName($distribution_channel_id, $book_name)
  1986. {
  1987. return OfficialImgtextUrls::getOfficialImgTxtUrlByBookName($distribution_channel_id, $book_name);
  1988. }
  1989. /**
  1990. * 上传二维码图片
  1991. */
  1992. static function uploadQrcodeImgToWechat($officialImgTxtUrlPrams)
  1993. {
  1994. $distribution_channel_id = $officialImgTxtUrlPrams['distribution_channel_id'];
  1995. $img_url = $officialImgTxtUrlPrams['qrcode_Img'];
  1996. $officialAccountprams['distribution_channel_id'] = $distribution_channel_id;
  1997. $officialAccounts = OfficialAccountService::officialAuthAccountBydistributionChannelId($officialAccountprams);
  1998. if (count($officialAccounts) > 0) {
  1999. $gzh_app_id = $officialAccounts[0]['appid'];
  2000. // $gzh_app_id = 'wxb2aaa55b088f12e9';
  2001. $timestamp = (time());
  2002. $group_nick = env('GROUP_NICK');
  2003. try {
  2004. $params = array("gzh_app_id" => $gzh_app_id, "img_url" => $img_url, "group_nick" => $group_nick, "timestamp" => $timestamp);
  2005. $sign = get_sign($params);
  2006. //获取封面图片media_id
  2007. $mediaCustomerJson = self::getUserClient()->request("GET", "upload_material_img/",
  2008. ['query' => ['gzh_app_id' => $gzh_app_id, 'img_url' => $img_url, 'group_nick' => env('GROUP_NICK'), 'timestamp' => $timestamp, 'sign' => $sign], 'connect_timeout' => 3]
  2009. )->getBody()->getContents();
  2010. \Log::info("============================上传二维码图片 通过图片+appid获取media_id");
  2011. \Log::info($mediaCustomerJson);
  2012. $mediaCustomerArray = json_decode($mediaCustomerJson, true);
  2013. if ($mediaCustomerArray['code'] == 1) {
  2014. $mediaCustomerData = $mediaCustomerArray['data'];
  2015. if (!empty($mediaCustomerData)) {
  2016. $thumb_media_id = $mediaCustomerData['media_id'];
  2017. $url = $mediaCustomerData['url'];
  2018. $wechatQrcodeImg['media_id'] = $thumb_media_id;
  2019. $wechatQrcodeImg['url'] = $url;
  2020. return $wechatQrcodeImg;
  2021. }
  2022. } else {
  2023. return false;
  2024. }
  2025. } catch (\Exception $e) {
  2026. \Log::info("============================上传二维码图片");
  2027. \Log::info($e->getMessage());
  2028. return false;
  2029. }
  2030. }
  2031. }
  2032. /**
  2033. * 删除图文素材
  2034. */
  2035. static function delOfficialImgTxtUrl($id)
  2036. {
  2037. try {
  2038. $officialImgtextUrl = OfficialImgtextUrls::officialImgtextUrlsById($id);
  2039. if (!empty($officialImgtextUrl)) {
  2040. $officialImgtextUrl['del_flag'] = 1;
  2041. $officialImgtextUrl->save();
  2042. return 1;
  2043. } else {
  2044. return 2;
  2045. }
  2046. } catch (\Exception $e) {
  2047. return 0;
  2048. }
  2049. }
  2050. //-------------------------------------------------生成图文链接End---------------------------
  2051. static public function getUserClient()
  2052. {
  2053. // return new Client(['base_uri' => 'http://118.31.133.29/api/']);
  2054. return new Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
  2055. }
  2056. /**
  2057. * 客服消息智能推送方法--简单公用版
  2058. * 以下3个板块找到对应的推送
  2059. * 1、用户
  2060. * 2、内容
  2061. * 3、队列类型
  2062. */
  2063. static function SimpleSmartPush($category_type)
  2064. {
  2065. if (empty($category_type)) return false;
  2066. \Log::info('simple_smart_push:' . $category_type);
  2067. // 应该不区分男女,通过内容来区分
  2068. $sexs = array('z');
  2069. $user_total_count = 0;
  2070. foreach ($sexs as $sex) {
  2071. \Log::info('smart_push_sex:' . $sex);
  2072. $send_content = '';
  2073. $skip = 0;
  2074. $loop = 0;
  2075. while ($skip <= 250000) {
  2076. $loop++;
  2077. $force_user = null;
  2078. $force_user = self::get_simple_send_users($category_type, $sex, $skip);
  2079. \Log::info('SmartPush_usernum:' . count($force_user) . ' loop:' . $loop . ' memory:' . memory_get_usage());
  2080. \Log::info('$force_user:' . json_encode($force_user));
  2081. $force_user_num = count($force_user);
  2082. $skip += $force_user_num;
  2083. $user_total_count += $force_user_num;
  2084. if ($force_user_num > 0) {
  2085. for ($i = 0; $i < $force_user_num; $i++) {
  2086. $uid = $force_user[$i]['uid'];
  2087. $bid = $force_user[$i]['bid'];
  2088. $template_id = $force_user[$i]['template_id'];
  2089. $distribution_channel_id = $force_user[$i]['distribution_channel_id'];
  2090. $send_content = self::get_simple_user_send_content($category_type, $uid, $distribution_channel_id);
  2091. if (empty($send_content)) {
  2092. \Log::info('smart_push:openid:' . $force_user[$i]['openid'] . ' appid:' . $force_user[$i]['appid'] . ' content_is_null');
  2093. continue;
  2094. }
  2095. $smart_push_queue = self::get_simple_smart_push_queue($category_type);
  2096. $data = array();
  2097. $data['openid'] = $force_user[$i]['openid'];
  2098. $data['appid'] = $force_user[$i]['appid'];
  2099. $data['type'] = 'one_task';
  2100. $data['task_id'] = 3;
  2101. $data['send_time'] = date("Y-m-d H:i:s");
  2102. if ($smart_push_queue['queue'] == 'send_template_list') {
  2103. $data['statusstr'] = (time());
  2104. $data['template_id'] = $template_id;
  2105. $data['url'] = $send_content['url'];
  2106. $data['template_content'] = json_encode($send_content['content']);
  2107. } elseif ($smart_push_queue['queue'] == 'send_news_list') {
  2108. $data['news_content'] = json_encode($send_content['content']);
  2109. } else {
  2110. $data['content'] = $send_content['content'];
  2111. }
  2112. $send_data = array(
  2113. 'send_time' => date("Y-m-d H:i:s"),
  2114. 'data' => $data
  2115. );
  2116. $delay = 0;
  2117. // \Log::info('smart_push:'.json_encode($data));
  2118. if ($smart_push_queue['queue'] == 'send_news_list') {
  2119. $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
  2120. } elseif ($smart_push_queue['queue'] == 'send_template_list') {
  2121. $job = (new SendTemplate($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
  2122. } else {
  2123. $job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
  2124. }
  2125. dispatch($job);
  2126. \Log::info('smart_push_user_end:' . $uid . ' memory:' . memory_get_usage());
  2127. // 释放内存
  2128. $send_data = $data = null;
  2129. }//end users
  2130. if ($force_user_num < 10000)//低于单次获取的10000条,所以下次不必获取,必须与单次获取的数值保持一致!
  2131. {
  2132. \Log::info('simple_smart_push user num less than once get num, so break category_type:' . $category_type . ' sex:' . $sex . ' loop:' . $loop . ' memory:' . memory_get_usage());
  2133. break;
  2134. }
  2135. } else {
  2136. \Log::info('simple_smart_push_has_no_user category_type:' . $category_type . ' sex:' . $sex . ' loop:' . $loop . ' memory:' . memory_get_usage());
  2137. break;
  2138. }
  2139. }//end loop
  2140. } // end sex
  2141. }
  2142. /**
  2143. * 得到指定用户,发送的图文内容
  2144. */
  2145. static function get_simple_user_send_content($category_type, $uid, $distribution_channel_id)
  2146. {
  2147. $send_content = null;
  2148. // 推荐图书
  2149. if ($category_type == 'template_short_long_chapter') {
  2150. $book_config = DataAnalysisBookConfig::getUserOneNotOrderBook($uid);
  2151. //
  2152. $template_content = [
  2153. 'first' => $book_config['template_title'],
  2154. 'keyword1' => '《' . $book_config['book_name'] . '》',
  2155. 'keyword2' => '今日',
  2156. 'remark' => '点击查看详情'
  2157. ];
  2158. $send_content['content'][] = $template_content;
  2159. $bookUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com';
  2160. $bookUrl = $bookUrl . '/reader?bid=' . Hashids::encode($book_config['bid']) . '&cid=' . $book_config['first_cid'] . '&fromtype=test_long_short_chapter';
  2161. $send_content['url'] = $bookUrl;
  2162. } elseif ($category_type == 'custom_short_long_chapter') {
  2163. $book_config = DataAnalysisBookConfig::getUserOneNotOrderBook($uid);
  2164. //
  2165. $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
  2166. $book['image'] = $promotionImages[0]['link'];
  2167. $bookUrl = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com';
  2168. $bookUrl = $bookUrl . '/reader?bid=' . Hashids::encode($book_config['bid']) . '&cid=' . $book_config['first_cid'] . '&fromtype=test_long_short_chapter';
  2169. $booksArray[0] = [['title' => $book_config->custom_title], ['description' => $book_config->custom_title], ['url' => $bookUrl], ['image' => $book['image']]];
  2170. $send_content['content'] = $booksArray;
  2171. } else {
  2172. }
  2173. \Log::info('get_simple_user_send_content_last:' . $uid);
  2174. \Log::info($send_content);
  2175. return $send_content;
  2176. }
  2177. /**
  2178. * 得到指定类型智能推送发送的用户列表
  2179. */
  2180. static function get_simple_send_users($category_type, $sex, $skip = 0)
  2181. {
  2182. $force_users = [];
  2183. $param = [];
  2184. // 客服消息
  2185. if ($category_type == 'custom_short_long_chapter') {
  2186. $uids = self::get_test_users();
  2187. // 42小时后
  2188. $param['subscribe_time'] = 'k';
  2189. $force_users = ForceSubscribeService::simpleForceUserCountByPrams($uids, $param, $skip);
  2190. $force_users = self::get_unique_users($force_users, 'custom_short_long_chapter', 7200);
  2191. } elseif ($category_type == 'template_short_long_chapter') {
  2192. $uids = self::get_test_users();
  2193. // 60小时后
  2194. $param['subscribe_time'] = 'm';
  2195. $param['common_template_id'] = 'OPENTM401671396';
  2196. \Log::info('start_simple_param:' . json_encode($uids) . ' param:' . json_encode($param));
  2197. $force_users = ForceSubscribeService::simpleForceUserCountByPrams($uids, $param, $skip);
  2198. \Log::info('before_unique_user:' . json_encode($force_users));
  2199. $force_users = self::get_unique_users($force_users, 'custom_short_long_chapter', 7200);
  2200. }
  2201. // key重新排序
  2202. $temp_force_users = array();
  2203. if (!empty($force_users)) {
  2204. foreach ($force_users as $force_user) {
  2205. $temp_force_users[] = $force_user;
  2206. }
  2207. }
  2208. return $temp_force_users;
  2209. }
  2210. static function get_simple_smart_push_queue($category_type)
  2211. {
  2212. $smart_push_queue = array();
  2213. $template_queue = array('template_short_long_chapter');
  2214. $custom_queue = array('custom_short_long_chapter');
  2215. $text_queue = array();
  2216. if (in_array($category_type, $template_queue)) {
  2217. $smart_push_queue['is_news'] = false;
  2218. $smart_push_queue['queue'] = 'send_template_list';
  2219. } elseif (in_array($category_type, $custom_queue)) {
  2220. $smart_push_queue['is_news'] = true;
  2221. $smart_push_queue['queue'] = 'send_news_list';
  2222. } else {
  2223. $smart_push_queue['is_news'] = false;
  2224. $smart_push_queue['queue'] = 'send_texts_list';
  2225. }
  2226. \Log::info('$smart_push_queue');
  2227. \Log::info($smart_push_queue);
  2228. return $smart_push_queue;
  2229. }
  2230. static function get_minus_test_users($force_users)
  2231. {
  2232. $test_uids = self::get_test_users();
  2233. \Log::info('get_minus_test_users,force_users:' . json_encode($force_users) . ' $test_uids:' . json_encode($test_uids));
  2234. if (!empty($force_users)) {
  2235. foreach ($force_users as $key => $force_user) {
  2236. if (in_array($force_user->uid, $test_uids)) {
  2237. \Log::info('get_minus_test_users_exist:' . $force_user->uid);
  2238. unset($force_users[$key]);
  2239. } else {
  2240. \Log::info('get_minus_test_users_not_exist:' . $force_user->uid);
  2241. }
  2242. }
  2243. }
  2244. \Log::info('get_minus_test_users after_force_users:' . json_encode($force_users));
  2245. return $force_users;
  2246. }
  2247. static function get_test_users()
  2248. {
  2249. // 获取测试的用户
  2250. $types = [2, 5];
  2251. $test_uids = DataAnalysisChapterService::getByTypes($types);
  2252. return $test_uids;
  2253. }
  2254. /**
  2255. * 拼接html的图文形式的素材
  2256. * @param unknown_type $bid
  2257. * @param unknown_type $chapter_num
  2258. * @return string
  2259. */
  2260. public static function get_push_chapter_content($bid, $chapter_num)
  2261. {
  2262. $chapters = Chapter::where('bid', $bid)->orderBy('sequence')->limit($chapter_num)->get();
  2263. if (empty($chapters)) {
  2264. \Log::info('get_push_chapter_content_empty:' . $bid);
  2265. return '';
  2266. }
  2267. $push_content = '';
  2268. $template_begin =
  2269. '<section class="novel-content">
  2270. <section class="cover-wrap cover-wrap__text">
  2271. <img src="">
  2272. </section>
  2273. <section class="article-text" style="font-size: 18px;">';
  2274. $push_content .= $template_begin;
  2275. foreach ($chapters as $chapter) {
  2276. $template_title_begin = '
  2277. <section class="article">
  2278. <section style="max-width: 100%; color: rgb(62, 62, 62); font-size: 18px; line-height: 28.4444px; white-space: normal; font-family: 微软雅黑;box-sizing: border-box !important; overflow-wrap: break-word !important; background-color: rgb(255, 255, 255);">
  2279. <section style="max-width: 100%; box-sizing: border-box; border-width: 0px; border-style: none; border-color: currentcolor; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; overflow-wrap: break-word !important;">
  2280. <section style="margin-top: 10px; margin-bottom: 10px; max-width: 100%; box-sizing: border-box; text-align: center; overflow-wrap: break-word !important;">
  2281. <section style="max-width: 100%; box-sizing: border-box; display: inline-block; vertical-align: middle; overflow-wrap: break-word !important;">
  2282. <section style="max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">
  2283. <section style="max-width: 100%; box-sizing: border-box; width: 5px; height: 2px; border-radius: 3px 3px 0px 0px; float: left; overflow-wrap: break-word !important; background-color: rgb(218, 203, 158);">
  2284. </section>
  2285. <section style="max-width: 100%; box-sizing: border-box; width: 5px; height: 2px; border-radius: 3px 3px 0px 0px; float: right; overflow-wrap: break-word !important; background-color: rgb(218, 203, 158);">
  2286. </section>
  2287. <section style="max-width: 100%; box-sizing: border-box; clear: both; overflow-wrap: break-word !important;">
  2288. </section>
  2289. </section>
  2290. <section style="padding: 2px 10px; max-width: 100%; box-sizing: border-box; border-left: 5px solid rgb(218, 203, 158); border-right: 5px solid rgb(218, 203, 158); border-color: rgb(218, 203, 158); color: rgb(255, 255, 255); overflow-wrap: break-word !important; background-color: rgb(249, 110, 87);">
  2291. <section class="" data-brushtype="text" style="max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">
  2292. ';
  2293. // $push_content .= $template_title_begin;
  2294. $template_article_title = isset($chapter->name) ? $chapter->name : '';
  2295. // $push_content .= $template_article_title;
  2296. $template_title_end = '
  2297. </section>
  2298. </section>
  2299. <section style="max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">
  2300. <section style="max-width: 100%; box-sizing: border-box; width: 5px; height: 2px; border-radius: 0px 0px 3px 3px; float: left; overflow-wrap: break-word !important; background-color: rgb(218, 203, 158);">
  2301. </section>
  2302. <section style="max-width: 100%; box-sizing: border-box; width: 5px; height: 2px; border-radius: 0px 0px 3px 3px; float: right; overflow-wrap: break-word !important; background-color: rgb(218, 203, 158);">
  2303. </section>
  2304. <section style="max-width: 100%; box-sizing: border-box; clear: both; overflow-wrap: break-word !important;">
  2305. </section>
  2306. </section>
  2307. </section>
  2308. </section>
  2309. </section>
  2310. <section>
  2311. ';
  2312. // $push_content .= $template_title_end;
  2313. $p_contents = isset($chapter->content) ? $chapter->content : '';
  2314. // 切割成单个P标签
  2315. $p_one_contents = explode(PHP_EOL, $p_contents);
  2316. if (!empty($p_one_contents)) {
  2317. foreach ($p_one_contents as $p_one_content) {
  2318. $one_content = '
  2319. <p style="text-indent: 2em; margin-top: 0.8em;">' .
  2320. $p_one_content .
  2321. '</p>';
  2322. $push_content .= $one_content;
  2323. }
  2324. }
  2325. $content_end = '
  2326. </section>
  2327. </section>
  2328. </section>
  2329. ';
  2330. $push_content .= $content_end;
  2331. }
  2332. $template_end = '
  2333. </section>
  2334. <section>
  2335. <img style="margin: auto; display: none;" src="">
  2336. </section>
  2337. <section class="novel-guide">
  2338. <div>
  2339. <section style="border:none; border-style: none; margin: 5px 0 0; padding: 10px; background: none;">
  2340. <section class="color" style="margin-top: -1px; margin-bottom: 0; min-height: 40px; visibility: visible; height: 40px; line-height: 40px; border-radius: 3px; text-align: center; color: rgb(255, 255, 255); background-color: rgb(191, 215, 48);">
  2341. <span style="font-size:14px;color: #000;">
  2342. ↓点击下方
  2343. <span style="color: #fff;">
  2344. “阅读原文”
  2345. </span>
  2346. 查看更多
  2347. </span>
  2348. </section>
  2349. <section class="border" style="margin: 0 auto 0 30px; float: none; width: 0; height: 0; border-left: 0 solid transparent; border-right: 18px solid transparent; border-top: 27px solid #bfd730;">
  2350. &nbsp;
  2351. </section>
  2352. </section>
  2353. </div>
  2354. </section>
  2355. </section>
  2356. ';
  2357. $push_content .= $template_end;
  2358. \Log::info('$push_content');
  2359. \Log::Info($push_content);
  2360. return $push_content;
  2361. }
  2362. }