Skip to content

Commit

Permalink
Merge pull request #41 from kbdxbt/master
Browse files Browse the repository at this point in the history
wx-template-msg
  • Loading branch information
jianyan74 authored Sep 12, 2019
2 parents 2589e55 + 96f3a93 commit cc5e1ea
Show file tree
Hide file tree
Showing 6 changed files with 334 additions and 0 deletions.
46 changes: 46 additions & 0 deletions api/modules/v1/controllers/MiniProgramController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use common\helpers\ResultDataHelper;
use common\models\member\Auth;
use common\enums\CacheKeyEnum;
use common\models\wechat\FormId;

/**
* 小程序授权验证
Expand Down Expand Up @@ -152,6 +153,51 @@ public function actionQrCode()
}
}

/**
* 记录小程序formid
*
* @return mixed
*/
public function actionFormId()
{
$model = new FormId();
$model->attributes = Yii::$app->request->post();

if (!$model->validate()) {
return ResultDataHelper::api(422, $this->getError($model));
}

$model->member_id = Yii::$app->user->identity->member_id;
$model->merchant_id = $this->getMerchantId();

return Yii::$app->services->wechatTemplateMsg->addFormId($model);
}

/**
* 发送小程序模板消息
*
* @return mixed
*/
public function actionSend()
{
$member_id = Yii::$app->user->identity->member_id;
$data = [
'touser' => 'openid',
'weapp_template_msg' => [
'template_id' => '*****',
'page' => 'index',
'form_id' => Yii::$app->services->wechatTemplateMsg->getFormId($member_id), //建议采用系统存储formid的形式获取
'data' => [
"keyword1" => '关键字1',
],
],
// 小程序绑定公众号发送模板消息
// 'mp_template_msg' => [
// ]
];
return Yii::$app->services->wechatTemplateMsg->send($data);
}

/**
* 权限验证
*
Expand Down
87 changes: 87 additions & 0 deletions common/models/wechat/FormId.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

namespace common\models\wechat;

use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;

/**
* This is the model class for table "rf_wechat_form_id".
*
* @property string $id
* @property string $merchant_id 商户id
* @property string $form_id formid
* @property string $stoped_at 失效时间
* @property string $created_at 创建时间
* @property string $updated_at 修改时间
*/
class FormId extends \common\models\base\BaseModel
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'rf_wechat_form_id';
}

/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['merchant_id', 'stoped_at', 'created_at', 'updated_at'], 'integer'],
[['form_id'], 'required'],
[['form_id'], 'string', 'max' => 100],
];
}

/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'merchant_id' => '商户id',
'member_id' => '用户id',
'form_id' => 'formid',
'stoped_at' => '失效时间',
'created_at' => '创建时间',
'updated_at' => '修改时间',
];
}

/**
* @param bool $insert
* @return bool
* @throws \yii\base\Exception
*/
public function beforeSave($insert)
{
if ($this->isNewRecord) {
// 小程序formid有效时间为7天
$this->stoped_at = time() + 7 * 24 * 60 * 60 - 60;
}

return parent::beforeSave($insert);
}

/**
* @return array
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
]
];
}
}
32 changes: 32 additions & 0 deletions common/queues/WxTemplateMsgJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php
namespace common\queues;

use Yii;
use yii\base\BaseObject;

/**
* 发送微信模板消息
*
* Class WxTemplateMsgJob
* @package common\queues
* @author kbdbxt
*/
class WxTemplateMsgJob extends BaseObject implements \yii\queue\JobInterface
{
/**
* 数据
*
* @array
*/
public $data;

/**
* @param \yii\queue\Queue $queue
* @return mixed|void
* @throws \yii\base\InvalidConfigException
*/
public function execute($queue)
{
Yii::$app->services->wechatTemplateMsg->realSend($this->data);
}
}
42 changes: 42 additions & 0 deletions console/migrations/m190908_032821_wechat_form_id.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

use yii\db\Migration;

/**
* Class m190908_032821_wechat_form_id
*/
class m190908_032821_wechat_form_id extends Migration
{
public function up()
{
/* 取消外键约束 */
$this->execute('SET foreign_key_checks = 0');

/* 创建表 */
$this->createTable('{{%wechat_form_id}}', [
'id' => "int(10) unsigned NOT NULL AUTO_INCREMENT",
'merchant_id' => "int(10) unsigned DEFAULT '0' COMMENT '商户id'",
'member_id' => "int(10) NOT NULL COMMENT '用户id'",
'form_id' => "varchar(100) NOT NULL DEFAULT '' COMMENT 'formid'",
'stoped_at' => "int(10) unsigned DEFAULT '0' COMMENT '失效时间'",
'created_at' => "int(10) unsigned DEFAULT '0' COMMENT '创建时间'",
'updated_at' => "int(10) unsigned DEFAULT '0' COMMENT '修改时间'",
'PRIMARY KEY (`id`)'
], "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

/* 索引设置 */

/* 表数据 */

/* 设置外键约束 */
$this->execute('SET foreign_key_checks = 1;');
}

public function down()
{
$this->execute('SET foreign_key_checks = 0');
/* 删除表 */
$this->dropTable('{{%wechat_form_id}}');
$this->execute('SET foreign_key_checks = 1;');
}
}
5 changes: 5 additions & 0 deletions services/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
* @property \services\wechat\RuleKeywordService $wechatRuleKeyword 规则关键字
* @property \services\wechat\RuleKeywordStatService $wechatRuleKeywordStat 规则关键字统计
* @property \services\wechat\ReplyDefaultService $wechatReplyDefault 默认回复
* @property \services\wechat\TemplateMsgService $wechatTemplateMsg 模板消息
* @property \services\member\MemberService $member 会员
* @property \services\member\AuthService $memberAuth 会员第三方授权
* @property \services\member\AddressService $memberAddress 会员收货地址
Expand Down Expand Up @@ -102,6 +103,10 @@ class Application extends Service
'wechatRuleKeyword' => 'services\wechat\RuleKeywordService',
'wechatRuleKeywordStat' => 'services\wechat\RuleKeywordStatService',
'wechatReplyDefault' => 'services\wechat\ReplyDefaultService',
'wechatTemplateMsg' => [
'class' => 'services\wechat\TemplateMsgService',
'queueSwitch' => true, // 是否丢进队列
],
/** ------ 用户 ------ **/
'member' => 'services\member\MemberService',
'memberAuth' => 'services\member\AuthService',
Expand Down
122 changes: 122 additions & 0 deletions services/wechat/TemplateMsgService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
<?php
namespace services\wechat;

use common\helpers\ArrayHelper;
use common\queues\WxTemplateMsgJob;
use Yii;
use common\components\Service;
use common\models\wechat\FormId;
use yii\web\UnprocessableEntityHttpException;

/**
* Class TemplateMsgService
* @package services\wechat
* @author kbdxbt
*/
class TemplateMsgService extends Service
{
/**
* formid保留次数
* @var int
*/
public $form_count = 10;

/**
* 消息队列
*
* @var bool
*/
public $queueSwitch = false;

/**
* 发送模板消息
*
* ```php
* Yii::$app->services->wechatTemplateMsg->send($data)
* ```
* @param array $data 模板数据
*/
public function send($data)
{
if ($this->queueSwitch == true) {
$messageId = Yii::$app->queue->push(new WxTemplateMsgJob([
'data' => $data,
]));

return $messageId;
}

return $this->realSend($data);
}

/**
* 发送 (发送不成功请先检查系统微信参数是否配置)
* 微信小程序统一服务消息接口(格式参考文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/uniform-message/uniformMessage.send.html)
* 微信公众号模板消息(格式参考文档:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html)
* @param $data
* @return bool
* @throws \yii\base\UnprocessableEntityHttpException
*/
public function realSend($data)
{
try {
if (isset($data['weapp_template_msg']) || isset($data['mp_template_msg'])) {
// 微信小程序统一服务消息接口
$result = Yii::$app->wechat->miniProgram->uniform_message->send($data);
} else {
// 微信公众号模板消息
$result = Yii::$app->wechat->app->template_message->send($data);
}
Yii::info($result);
if ($result['errcode'] != 0) {
throw new UnprocessableEntityHttpException('模板消息发送失败:'.$result['errcode']);
}
return true;
} catch (\Exception $e) {
Yii::error($e->getMessage());
throw new UnprocessableEntityHttpException($e->getMessage());
}

return false;
}

/**
* 获取formid
* @param $member_id
*/
public function getFormId($member_id)
{
$model = FormId::find()
->filterWhere(['merchant_id' => $this->getMerchantId()])
->andWhere(['member_id' => $member_id])
->andWhere(['>', 'stoped_at', time()])
->orderBy('created_at asc')
->one();

if (!$model) {
throw new \yii\web\UnprocessableEntityHttpException('未找到formid');
}
$form_id = $model->form_id;
$model->delete();

return $form_id;
}

/**
* 存储formid
* @param FormId $model
*/
public function addFormId(FormId $model)
{
$count = FormId::find()
->filterWhere(['merchant_id' => $this->getMerchantId()])
->andWhere(['member_id' => $model->member_id])
->andWhere(['>', 'stoped_at', time()])
->count();

if ($count < $this->form_count) {
$model->save();
}
return;
}
}

0 comments on commit cc5e1ea

Please sign in to comment.