zm
2021-04-01 802c31297a1ae5b8c2e8fb5c62e9790dfc5d7583
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
/**
 * link: http://www.zjhejiang.com/
 * copyright: Copyright (c) 2018 浙江禾匠信息科技有限公司
 * author: xay
 */
 
namespace app\jobs;
 
use app\forms\common\CommonOption;
use app\forms\common\mptemplate\MpTplMessage;
use app\models\MpTemplateRecord;
use app\models\Option;
use yii\base\BaseObject;
use yii\queue\JobInterface;
 
class MpTplMessageJob extends BaseJob implements JobInterface
{
    public $mall;
    public $token;
    public $url;
    public $templateId;
    public $data;
    public $miniprogram;
 
    public $admin_open_list = [];
    public $app_id;
    public $app_secret;
    /**
     * @param \yii\queue\Queue $queue
     * @throws \Exception
     */
    public function execute($queue)
    {
        try {
            $this->setRequest();
            $logs = [];
            $count = 0;
 
            foreach ($this->admin_open_list as $item) {
                //发送数据
                $args = [
                    'touser' => $item['open_id'],
                    'template_id' => $this->templateId,
                    'data' => $this->data,
                ];
 
                $log = [
                    'open_id' => $args['touser'],
                    'mall_id' => $this->mall->id,
                    'status' => 1,
                    'data' => \Yii::$app->serializer->encode($args),
                    'error' => '',
                    'created_at' => mysql_timestamp(),
                    'token' => $this->token,
                ];
 
                try {
                    $res = (new MpTplMessage())->senderMsg($args, [
                        'app_id' => $this->app_id,
                        'app_secret' => $this->app_secret,
                        'mall_id' => $this->mall->id,
                    ]);
                } catch (\Exception $e) {
                    \Yii::error($e);
                    $log['error'] = $e->getMessage();
                    $log['status'] = 0;
                }
                $count++;
                $logs[] = $log;
            }
 
            if ($count > 0) {
                \Yii::$app->db->createCommand()->batchInsert(
                    MpTemplateRecord::tableName(),
                    ['open_id', 'mall_id', 'status', 'data', 'error', 'created_at', 'token'],
                    $logs
                )->execute();
            }
        } catch (\Exception $e) {
            \Yii::warning($e);
            throw $e;
        }
    }
}