WechatMsgController.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\modules\common\controllers;
  8. //include_once '../../../utils/Wechat/crypt/wxBizMsgCrypt.php';
  9. use app\models\DeliveryInfo;
  10. use app\models\Order;
  11. use app\models\Store;
  12. use app\models\WechatConfig;
  13. use app\models\WechatMenuConfig;
  14. use app\utils\Delivery\Delivery;
  15. use EasyWeChat\Factory;
  16. use yii\web\Controller;
  17. use EasyWeChat\Kernel\Messages\News;
  18. use EasyWeChat\Kernel\Messages\NewsItem;
  19. /**
  20. * 配送单回调消息通知
  21. * Class DeliveryController
  22. * @package app\modules\common\controllers
  23. */
  24. class WechatMsgController extends Controller
  25. {
  26. /**
  27. * @var Store $store
  28. */
  29. public $store;
  30. /**
  31. * 配送消息推送event
  32. */
  33. const WAYBILL_EVENT = 'update_waybill_status';
  34. private static $validEvent = [
  35. self::WAYBILL_EVENT
  36. ];
  37. /**
  38. * [
  39. * 'signature' => '49d0de53b76cd91e1ce606a4b0ca26cb57144a07',
  40. * 'timestamp' => '1635318076',
  41. * 'nonce' => '1091106830',
  42. * 'ToUserName' => 'gh_c32588e3eaaf',
  43. * 'FromUserName' => 'or1pO5cEyXqa3al4iVCaXQy-oC-E',
  44. * 'CreateTime' => 1635318076,
  45. * 'MsgType' => 'event',
  46. * 'Event' => 'update_waybill_status',
  47. * 'shopid' => 'test_shop_id',
  48. * 'shop_order_id' => 'tianxin100',
  49. * 'waybill_id' => 'test_waybill_id',
  50. * 'action_time' => 1635318076,
  51. * 'order_status' => 103,
  52. * 'action_msg' => '',
  53. * 'agent' => [
  54. * 'name' => '',
  55. * 'phone' => '',
  56. * ],
  57. * 'shop_no' => '',
  58. * ]
  59. */
  60. public function actionIndex() {
  61. $params = post_params();
  62. \Yii::error($params);
  63. if($_GET["echostr"]){
  64. if ($this->checkSignature()) {
  65. return $_GET["echostr"];
  66. }
  67. }
  68. $order = Order::findOne($params['shop_order_id']);
  69. $this->store = Store::findOne($order->store_id);
  70. if (!$this->store) {
  71. \Yii::error(['即时配送状态更改回调===============>', '获取商户信息失败']);
  72. return;
  73. }
  74. if (!$this->checkSignature()) {
  75. \Yii::error(['即时配送状态更改回调===============>', '验签失败']);
  76. return;
  77. }
  78. // 即时配送状态更新
  79. if (in_array($params['Event'], self::$validEvent)) {
  80. try {
  81. return $this->handleDeliveryOrderStatus($params);
  82. } catch (\Exception $e) {
  83. \Yii::error('---------===========');
  84. \Yii::error(json_encode($e));
  85. }
  86. }
  87. }
  88. /**
  89. * 测试接入
  90. * @return bool
  91. */
  92. private function checkSignature()
  93. {
  94. $signature = $_GET["signature"];
  95. $timestamp = $_GET["timestamp"];
  96. $nonce = $_GET["nonce"];
  97. $token = $this->store->wechat_msg_token ?: 'weixin';
  98. $tmpArr = array($token, $timestamp, $nonce);
  99. sort($tmpArr, SORT_STRING);
  100. $tmpStr = implode( $tmpArr );
  101. $tmpStr = sha1( $tmpStr );
  102. if ($tmpStr == $signature ) {
  103. return true;
  104. } else {
  105. return false;
  106. }
  107. }
  108. private function handleDeliveryOrderStatus($data) {
  109. $delivery_info = DeliveryInfo::findOne(['store_id' => $this->store->id, 'order_no' => $data['shop_order_id'], 'waybill_id' => $data['waybill_id']]);
  110. if (!$delivery_info) {
  111. \Yii::error(['即时配送状态更改回调===============>', '获取商户信息失败']);
  112. return;
  113. }
  114. $delivery_info->status = $data['order_status'];
  115. $delivery_info->updated_at = $data['action_time'];
  116. if (!empty($data['agent']['name']) && !empty($data['agent']['phone'])) {
  117. $delivery_info->rider_name = $data['agent']['name'];
  118. $delivery_info->rider_mobile = $data['agent']['phone'];
  119. }
  120. if (!$delivery_info->save()) {
  121. \Yii::error(['即时配送状态更改回调===============>', '更新数据状态失败']);
  122. return;
  123. }
  124. $order = Order::findOne(['order_no' => $data['shop_order_id']]);
  125. if (in_array($data['order_status'], Delivery::$validRiderGetGoods)) {
  126. $order->trade_status = Order::ORDER_FLOW_SEND;
  127. }
  128. if (in_array($data['order_status'], Delivery::$validComplete)) {
  129. $order->trade_status = Order::ORDER_FLOW_CONFIRM;
  130. }
  131. if (in_array($data['order_status'], Delivery::$validError)) {
  132. $order->trade_status = Order::ORDER_FLOW_CANCEL;
  133. }
  134. $order->save();
  135. return 'success';
  136. }
  137. // private function decryptMsg() {
  138. //
  139. // $pc = new \WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->app_id);
  140. //
  141. //
  142. // $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  143. // $from_xml = sprintf($format, $encrypt);
  144. //
  145. // // 第三方收到公众号平台发送的消息
  146. // $msg = '';
  147. // $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
  148. // if ($errCode == 0) {
  149. // \Yii::error("解密后: " . $msg . "\n");
  150. // } else {
  151. // \Yii::error($errCode . "\n");
  152. // }
  153. // }
  154. public function actionApi() {
  155. try {
  156. $store_id = get_store_id();
  157. $wechat_config = WechatConfig::findOne(['store_id' => $store_id, 'type' => 2, 'is_delete' => 0]);
  158. $config = [];
  159. if ($wechat_config && $wechat_config->app_secret && $wechat_config->app_id && $wechat_config->ext) {
  160. $ext = json_decode($wechat_config->ext, true);
  161. $token = $ext['token'] ?: '';
  162. $config = [
  163. 'app_id' => $wechat_config->app_id,
  164. 'secret' => $wechat_config->app_secret,
  165. // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
  166. 'response_type' => 'array',
  167. 'token' => $token
  168. ];
  169. $app = Factory::officialAccount($config);
  170. $app->server->push(function ($message) {
  171. debug_log($message,'wechat_msg.log');
  172. switch ($message['Event']) {
  173. case "CLICK":
  174. if (strpos($message['EventKey'], 'news_') !== false) {
  175. $id = str_replace('news_', '', $message['EventKey']);
  176. debug_log($id,'wechat_msg.log');
  177. $menu_config = WechatMenuConfig::findOne($id);
  178. debug_log($menu_config->value,'wechat_msg.log');
  179. if ($menu_config->value) {
  180. $value = json_decode($menu_config->value, true);
  181. $title = $value['title'];
  182. $pic = $value['pic'];
  183. $link = $value['link'];
  184. $desc = $value['desc'];
  185. $items = [
  186. new NewsItem([
  187. 'title' => $title,
  188. 'description' => $desc,
  189. 'url' => $link,
  190. 'image' => $pic,
  191. // ...
  192. ]),
  193. ];
  194. return new News($items);
  195. }
  196. }
  197. }
  198. return '您好,欢迎使用';
  199. });
  200. $response = $app->server->serve();
  201. $response->send();
  202. return $response;
  203. }
  204. } catch (\Exception $e) {
  205. debug_log($e->getMessage(),'wechat_msg.log');
  206. }
  207. }
  208. }