| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213 |
- <?php
- namespace api\controllers;
- use common\enums\StatusEnum;
- use common\events\census\SubscribeEvent;
- use common\helpers\FormatHelper;
- use common\helpers\WechatHelper;
- use common\models\wechat\ReplyRule;
- use common\models\wechat\RuleKeyword;
- use common\models\wechat\WechatSubscribe;
- use EasyWeChat\Kernel\Messages\Text;
- use Yii;
- use yii\web\NotFoundHttpException;
- use common\models\order\Order;
- use common\models\common\PaymentTradeOrder;
- use common\models\user\User;
- use addons\YunfastPay\common\models\PaymentTrade;
- class WechatController extends OnAuthController
- {
- public $enableCsrfValidation = false;
- public $modelClass = '';
- protected $authOptional = ['index'];
- protected function verbs() {
- $verbs = parent::verbs();
- $verbs['index'] = ['POST','GET','HEAD']; //methods you need in action
- return $verbs;
- }
- /**
- *
- * 接收公众号信息
- * @Author: lun
- * @DateTime: 2021/12/8 0008 17:38
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @return array|mixed|null
- * @throws NotFoundHttpException
- * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
- * @throws \ReflectionException
- */
- public function actionIndex()
- {
- $mall_id = $this->mall_id;
- // 微信公众号配置
- $request = Yii::$app->request;
- Yii::$app->params['wechatConfig'] = Yii::$app->services->setting->mall->get($mall_id, 'wechat');
- switch ($request->getMethod()) {
- // 激活公众号
- case 'GET':
- if (WechatHelper::verifyToken($request->get('signature'), $request->get('timestamp'), $request->get('nonce'))) {
- echo $request->get('echostr');
- exit;
- }
- throw new NotFoundHttpException('签名验证失败.');
- break;
- // 接收数据
- case 'POST':
- /** @var \jianyan\easywechat\Wechat $wechat */
- $wechat = Yii::$app->wechat;
- $app = $wechat->app;
- $app->server->push(function ($message) use ($mall_id) {
- try {
- Yii::error('接收到微信信息:'.json_encode($message));
- switch ($message['MsgType']) {
- case 'event': // '收到事件消息';
- $reply = $this->event($mall_id, $message);
- break;
- case 'text':
- //文字消息
- $reply = RuleKeyword::match($message['Content'],$mall_id);
- break;
- default:
- // ... 其它消息(image、voice、video、location、link、file ...)
- $reply = new Text('您好,系统暂不支持接受此类信息');
- break;
- }
- return $reply;
- } catch (\Exception $e) {
- // 记录行为日志
- if (YII_DEBUG) return $e->getMessage();
- return '系统出错,请联系管理员';
- }
- });
- // 将响应输出
- $response = $app->server->serve();
- $response->send();
- break;
- default:
- throw new NotFoundHttpException('所请求的页面不存在.');
- }
- exit();
- }
- /**
- * 公众号事件
- * @Author: lun
- * @DateTime: 2021/12/8 0008 17:37
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $mall_id
- * @param $message
- * @return bool
- */
- protected function event($mall_id, $message)
- {
- // dd($message);
- switch ($message['Event']) {
- // 关注事件
- case 'subscribe':
- // 取消关注事件
- case 'unsubscribe':
- $res = self::handleSubscrible($mall_id, $message);
- break;
- // 二维码扫描事件
- case 'SCAN':
- $res = true;
- break;
- // 上报地理位置事件
- case 'LOCATION':
- //TODO 暂时不处理
- $res = true;
- break;
- // 自定义菜单(点击)事件
- case 'trade_manage_order_settlement':
- $res = self::tradeManageOrderSettlement($mall_id, $message);
- break;
- case 'CLICK':
- $content = $message['EventKey'];
- $res = RuleKeyword::match($content,$mall_id);
- }
- return $res;
- }
- /**
- * 关注公众号处理
- * @Author: lun
- * @DateTime: 2021/12/9 0009 14:46
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $message
- * @return bool
- */
- private static function handleSubscrible($mall_id, $message)
- {
- // 数据为空不做处理
- if (empty($message)) return true;
- try {
- $params = [
- 'to_user_name' => $message['ToUserName'] ?? '',
- 'from_user_name' => $message['FromUserName'] ?? '',// open_id
- 'create_time' => $message['CreateTime'] ?? '',
- 'msg_type' => $message['MsgType'] ?? '',
- 'event' => $message['Event'] ?? '',
- 'subscribe_status' => $message['Event'] === 'subscribe' ? 1 : 2,// 1=关注公众号,2=取消关注
- ];
- $res = WechatSubscribe::setData($mall_id, $params);
- if ($res == false) throw new \Exception(WechatSubscribe::getStaticError());
- if($params['subscribe_status'] == 1){
- \Yii::error('触发关注事件');
- $event = new SubscribeEvent($mall_id);
- $data = ['subscribe_status' => $params['subscribe_status'],'mall_id'=>$mall_id];
- \Yii::$app->services->events->dispatch($event, $data, $event->listeners);
- $model = ReplyRule::getOne([['mall_id'=>$mall_id,'status'=>StatusEnum::ENABLED,'is_follow_reply'=>1]]);
- if($model){
- return RuleKeyword::sendMessage($model);
- }
- }
- return true;
- } catch (\Exception $e) {
- $exception = FormatHelper::exception($e, "关注公众号处理");
- Yii::error($exception);
- return false;
- }
- }
- public static function tradeManageOrderSettlement($mall_id, $message){
- try {
- $where = [
- ['mall_id'=>$mall_id]
- ];
- if(!empty($message['transaction_id'])) $where[]= ['third_trade_no'=>$message['transaction_id']];
- if(!empty($message['merchant_trade_no'])) $where[]= ['out_trade_no'=>$message['merchant_trade_no']];
- if(empty($message['confirm_receive_time']))return true;
- $payment_trade = PaymentTrade::getOne($where);
- if(empty($payment_trade)) return true;
- $list = PaymentTradeOrder::lists(['where'=>[['trade_id'=>$payment_trade['id']]]]);
- if(empty($list)) return true;
- $order_nos = array_column($list,'order_no');
- $list = Order::lists([
- 'where'=>[['trade_id'=>$order_nos]]
- ]);
- $user = User::findOne(['id'=>$payment_trade['user_id']]);
- foreach ($list as $item){
- $params['mall_id'] = $mall_id;
- $params['user_id'] = $item['user_id'];
- $params['operator_id'] = $item['user_id'];
- $params['operator_name'] = !empty($user->nickname) ?$user->nickname:$user->mobile;
- $res = Order::takeDelivery($params);
- }
- return true;
- }catch (\Exception $e){
- $exception = FormatHelper::exception($e, "订单完成发货时");
- Yii::error($exception);
- return false;
- }
- }
- }
|