| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434 |
- <?php
- namespace common\helpers\wechat;
- use common\components\WechatCache;
- use common\enums\StatusEnum;
- use common\models\user\UserExtra;
- use common\models\user\UserInfo;
- use common\models\wechat\WechatSendMessageLog;
- use EasyWeChat\Factory;
- use common\models\common\MallSetting;
- use GuzzleHttp\Exception\GuzzleException;
- class WechatTemplate
- {
- private $wechat = null;
- private $mall_id;
- public $openid;
- private $user_id;
- private $notice_wechat; //['order_create'=>['tem_key' => 'OPENTM401424715', 'name' => '订单生成通知', 'tempid'=>'Fpjmfna8511']];
- private $is_logging = null;
- private $is_miniapp_priority = null;
- private $is_open = null;
- private $app_id = null;
- private $wechat_app_id = null;
- const PLATFORM_MP_MX = 'mp-wx'; //小程序
- const PLATFORM_WECHAT = 'wechat'; //公众号
- const ERRCODE_INVALID_TEMPLATE_ID = 40037; //微信公众号没有该模板id
- const ORDER_CREATE = 'order_create'; //订单创建
- const ORDER_CANCEL = 'order_cancel'; //订单取消通知
- const ORDER_SENT = 'order_sent'; //订单发货
- const ORDER_CONFIRMED = 'order_confirmed'; //订单确认收货
- const ORDER_PAY_SUCCESS = 'order_pay_success'; //订单支付成功
- const ORDER_REFUND_AGREE = 'order_refund_agree'; //退货申请通过提醒
- const COMMISSION_RECEIPT = 'commission_receipt';//佣金到账通知
- const TEAM_ADD = 'team_add';//渠道人员增加通知
- const WITHDRAWAL_SUCCESS = 'withdrawal_success';//提现成功通知
- const INVITATION_TO_REGISTER_SUCCESS = 'Invitation_to_register_success';//邀请注册成功通知
- const RECOMMEND_PAY_SUCCESS = 'recommend_pay_success';// 被推荐人支付成功模版
- const ORDER_REFUND_RESULT = 'order_refund_result';// 售后订单处理结果模板
- const STORE_ORDER_PAY_SUCCESS = 'store_order_pay_success';// 订单支付成功通知
- const ORDER_COMMISSION_SETTLE = 'order_commission_settle'; //佣金到账通知
- const DEFAULT_PAGE = 'default_page';// 默认页面
- // const GROUP_BY_SUCCESS = 'group_buy_success'; //拼团成功通知
- // const GROUP_BY_FAILED = 'group_buy_failed'; //拼团失败通知
- // const BALANCE_CHANE = 'balance_change'; //账户余额通知
- // const INCOME_CHANGE = 'income_change'; //账户余额通知
- // const SCORE_CHANGE = 'score_change'; //积分交易提醒
- // const ORDER_REFUND_AGREE = 'order_refund_agree'; //退货申请通过提醒
- // const ORDER_REFUND_REFUSE = 'order_refund_refuse'; //售后申请审核通知
- // const ORDER_REFUND_MONEY = 'order_refund_money'; //退款成功通知
- // const USER_REGISTER = 'userRegister'; //下线加入通知
- // const UP_LEVEL = 'upLevel'; //会员等级变更通知
- // const E_COUPON_SEND = 'e_coupon_send'; //电子券通知
- // const ACHIEVEMENT_GRANT_PUSH = 'achievement_grant_push'; //定期业绩通知
- public static function getPagePath($key)
- {
- $result = [
- self::DEFAULT_PAGE => 'pages/index/index',
- self::ORDER_CREATE => 'plugins/pages/order/detail',
- self::COMMISSION_RECEIPT => 'public/promotion/index?title=',
- self::TEAM_ADD => 'plugins/public/promotion/client',
- self::WITHDRAWAL_SUCCESS => 'plugins/pages/assets/balance/list?type=2',
- self::ORDER_REFUND_AGREE => 'plugins/pages/refund/detail',
- self::ORDER_COMMISSION_SETTLE => 'plugins/public/promotion/index?title=',
- ];
- if (isset($result[$key])) return $result[$key];
- return '';
- }
- public function __construct($mall_id)
- {
- $this->mall_id = $mall_id;
- $notice_wechat = MallSetting::getConfByGroup($this->mall_id, 'notice_wechat', true);
- if (empty($notice_wechat) || !isset($notice_wechat['template_message'])) {
- $this->notice_wechat = false;
- } else {
- $this->is_open = $notice_wechat['is_open'];
- $this->is_logging = $notice_wechat['is_logging'];
- $this->is_miniapp_priority = $notice_wechat['is_miniapp_priority'];
- $template_massage = $notice_wechat['template_message'];
- $this->notice_wechat = json_decode($template_massage['value'], true);
- $wechat_setting = \Yii::$app->services->setting->mall->get($mall_id, 'wechat');
- $mini_program = \Yii::$app->services->setting->mall->get($mall_id, 'mini_program');
- $this->app_id = $mini_program['app_id'] ?? '';
- $this->wechat_app_id = $wechat_setting['app_id'] ?? '';
- if (empty($wechat_setting)) {
- $this->notice_wechat = false;
- } else {
- unset($wechat_setting['name']);
- unset($wechat_setting['qrcode']);
- $platform = $this->getPlatForm();
- // switch ($platform) {
- // case self::PLATFORM_WECHAT:
- $this->wechat = Factory::officialAccount($wechat_setting);
- $this->wechat->access_token->setCache(new WechatCache());
- // break;
- // case self::PLATFORM_MP_MX:
- // $this->wechat = Factory::miniProgram($mini_program);
- // $this->wechat->access_token->setCache(new WechatCache());
- //
- // break;
- // }
- }
- }
- }
- public static function getMap(): array
- {
- return [
- self::ORDER_CREATE => '订单生成通知',
- self::ORDER_CANCEL => '订单取消通知',
- self::ORDER_SENT => '订单发货通知',
- self::ORDER_CONFIRMED => '订单确认收货通知',
- self::ORDER_PAY_SUCCESS => '订单支付成功通知',
- // self::ORDER_REFUND_AGREE => '退货申请通过通知',
- // self::COMMISSION_RECEIPT => '佣金到账通知',
- // self::TEAM_ADD => '渠道人员增加通知',
- self::WITHDRAWAL_SUCCESS => '提现成功通知',
- self::INVITATION_TO_REGISTER_SUCCESS => '邀请注册成功通知',
- self::RECOMMEND_PAY_SUCCESS => '好友付款成功通知',
- self::ORDER_REFUND_RESULT => '售后订单处理结果通知',
- self::STORE_ORDER_PAY_SUCCESS => '订单支付成功通知',
- self::ORDER_COMMISSION_SETTLE => '佣金到账通知',
- ];
- }
- /**
- * 开启消息模板推送
- * @return bool
- */
- public function is_open()
- {
- if ($this->wechat === null) return false;
- return empty($this->is_open) ? false : ($this->is_open['value'] == 1 ? true : false);
- }
- /**
- * 是否记录数据库日志
- * @return bool
- */
- public function is_logging()
- {
- if ($this->wechat === null) return false;
- return empty($this->is_logging) ? false : ($this->is_logging['value'] == 1 ? true : false);
- }
- /**
- * 用户是否开启推送
- */
- public function is_notice($user_id)
- {
- $user_extra = UserExtra::find()->where(['user_id' => $user_id])->one();
- return empty($user_extra) ? false : ($user_extra['is_wechat_notice'] == 1 ? true : false);
- }
- /**
- * @param $user_id
- * @return bool
- */
- public function is_platform_wechat($user_id)
- {
- $platform = $this->getPlatForm();
- $platform_key = self::PLATFORM_WECHAT;
- // switch ($platform) {
- // case self::PLATFORM_WECHAT:
- $platform_key = self::PLATFORM_WECHAT;
- // break;
- // case self::PLATFORM_MP_MX:
- // $platform_key = self::PLATFORM_MP_MX;
- // break;
- // }
- $user_info = UserInfo::find()->where(['mall_id' => $this->mall_id, 'status' => StatusEnum::ENABLED, 'user_id' => $user_id, 'platform' => $platform_key])->one();
- return !empty($user_info) && $this->openid = $user_info['openid'];
- }
- /**
- * 发送模板消息
- * @param $user_id
- * @param $template_key
- * @param $url
- * @param $data
- * @param null $miniapp_page
- * @param null $template_id
- * @return bool|void
- * @throws GuzzleException
- */
- public function sendTemplate($user_id, $template_key, $url, $data, $miniapp_page = null, $template_id = null)
- {
- if ($this->wechat == null) return;
- //商城是否开启推送模板消息
- if ($this->is_logging() === false) return false;
- //用户是否开启模板消息
- if ($this->is_notice($user_id) === false) return false;
- //是否公众号用户
- if ($this->is_platform_wechat($user_id) === false) return false;
- try {
- if ($template_id == null) {
- $template_id = $this->checkTemplate($template_key);
- if (!$template_id) return false;
- }
- $this->user_id = $user_id;
- $result = [];
- $platform = $this->getPlatForm();
- switch ($platform) {
- case self::PLATFORM_WECHAT:
- $result = $this->sendWechat($this->openid, $template_id, $url, $data);
- break;
- case self::PLATFORM_MP_MX:
- $result = $this->sendMiniApp($this->openid, $template_id, $url, $data, $miniapp_page);
- break;
- }
- //微信公众号数据没有该模板,删除本地数据库中的数据
- if (!empty($result['errcode']) && $result['errcode'] != 0) {
- \Yii::error('发送模板消息失败, error_code=' . $result['errcode'] . ',error_message=' . $result['errmsg']);
- }
- } catch (\Exception $e) {
- var_dump($e->getMessage());
- \Yii::error('发送模板消息失败,失败原因:' . $e->getMessage() . $e->getFile() . ',错误行数:' . $e->getLine());
- return false;
- }
- return true;
- }
- /**
- * 添加模板
- * 参考:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#获得模板ID
- * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
- * @throws GuzzleException
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
- */
- public function addTemplate($key,$template_id)
- {
- if(!empty($template_id)){
- $url = "cgi-bin/template/del_private_template";
- $post_data = ['template_id'=>$template_id];
- $this->wechat->template_message->httpPostJson($url, $post_data);
- }
- $params = $this->getTemplateInfo($key);
- $url = "cgi-bin/template/api_add_template";
- return $this->wechat->template_message->httpPostJson($url, $params);
- }
- /**
- * 获取对应模版消息
- * @return array
- */
- public function getTemplateInfo($key = null)
- {
- $data = [
- self::ORDER_CREATE => [// 用户下单成功通知-美妆
- 'template_id_short' => 48176,
- 'keyword_name_list' => ['订单编号','商品名称','下单时间','购买人','收货地址']
- ],
- self::ORDER_CANCEL => [// 订单取消通知-美妆
- 'template_id_short' => 48102,
- 'keyword_name_list' => ['订单编号','订单状态','取消原因']
- ],
- self::ORDER_PAY_SUCCESS => [// 付款成功通知-机械电子产品
- 'template_id_short' => 48847,
- 'keyword_name_list' => ['支付金额','商品名称','收货地址','订单编号']
- ],
- self::ORDER_SENT => [// 订单发货提醒-机械电子产品
- 'template_id_short' => 49296,
- 'keyword_name_list' => ['商品名称','订单编号','快递公司','快递单号','客户地址']
- ],
- self::ORDER_CONFIRMED => [// 确认收货通知参数-软件/建站/技术开发
- 'template_id_short' => 50439,
- 'keyword_name_list' => ['订单编号','商品名称','收货时间']
- ],
- self::WITHDRAWAL_SUCCESS => [// 提现成功通知-软件/建站/技术开发
- 'template_id_short' => 49581,
- 'keyword_name_list' => ['提现金额','提现日期']
- ],
- self::INVITATION_TO_REGISTER_SUCCESS => [// 用户注册成功通知-软件/建站/技术开发
- 'template_id_short' => 50810,
- 'keyword_name_list' => ['注册姓名','注册手机号','注册时间','注册来源']
- ],
- self::RECOMMEND_PAY_SUCCESS => [// 好友支付成功通知-软件/建站/技术开发
- 'template_id_short' => 49101,
- 'keyword_name_list' => ['订单编号','客户名称','付款日期','付款时间']
- ],
- self::ORDER_REFUND_RESULT => [// 商家自营-机械电子产品
- 'template_id_short' => 51562,
- 'keyword_name_list' => ['订单号', '处理时间', '处理结果']
- ],
- self::STORE_ORDER_PAY_SUCCESS => [// 商家自营-母婴用品
- 'template_id_short' => 61082,
- 'keyword_name_list' => ['订单号', '结算金', '结算时间']
- ],
- self::ORDER_COMMISSION_SETTLE => [ //佣金到账通知
- 'template_id_short' => 55697,
- 'keyword_name_list' => ['结算金额', '结算时间'],
- ],
- ];
- if (empty($data[$key])) throw new \Exception('暂无此消息模板');
- return $key ? $data[$key] : $data;
- }
- /**
- * @param $template_type
- * @return false|mixed
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- public function checkTemplate($template_type)
- {
- try {
- if (empty($this->notice_wechat)) return false;
- $template_massage = $this->notice_wechat;
- if (!isset($this->notice_wechat[$template_type])) return false;
- //获取
- if (!isset($this->notice_wechat[$template_type]['tempid'])) {
- if (!isset($this->notice_wechat[$template_type]['tem_key'])) return false;
- $data = $this->wechat->template_message->addTemplate($this->notice_wechat[$template_type]['tem_key']);
- if ($data['errcode'] == 0) {
- $template_massage[$template_type]['tempid'] = $data['template_id'];
- $setting = ['notice_wechat' => ['template_message' => json_encode($template_massage, JSON_UNESCAPED_UNICODE)]];
- \Yii::$app->services->setting->mall->set($this->mall_id, $setting);
- return $data['template_id'];
- } else {
- \Yii::error('发送模板消息失败,获取template_id失败,失败原因:' . $data['errmsg']);
- return false;
- }
- }
- return $this->notice_wechat[$template_type]['tempid'];
- } catch (\Exception $e) {
- \Yii::error('发送模板消息失败,获取template_id失败,失败原因:' . $e->getMessage() . ',错误行数:' . $e->getLine());
- return false;
- }
- }
- /**
- * 跳转平台
- * @return string
- */
- public function getPlatForm()
- {
- return $this->is_miniapp_priority['value'] == 1 ? 'mp-wx' : 'wechat';
- }
- /**
- * @param $touser
- * @param $template_id
- * @param $url
- * @param $data
- * [
- * 'touser' => 'owdRztxk_XOtVZ0xglXuGv_MsRbA',
- * 'template_id' => '7rTBQadzdA4qn2RSR0_6lYUJxBlR6HloEMl03AuPRK4',
- * 'url' => 'http://jxmall.com',
- * 'data' => [
- * 'productType' => '商品名称',
- * 'name' => '小米手机',
- * 'number' => 12,
- * 'expDate' => '永久有效',
- * 'remark' => '恭喜你,购买成功'
- * ],
- * ]
- *
- * @return array
- * {
- * "errcode": 0,
- * "errmsg": "ok",
- * "msgid": 1552413574407520257
- * }
- */
- public function sendWechat($touser, $template_id, $url, $data)
- {
- return $this->wechat->template_message->send([
- 'touser' => $touser,
- 'template_id' => $template_id,
- 'url' => $url,
- 'data' => $data
- ]);
- }
- /**
- * @param $touser
- * @param $template_id
- * @param $url
- * @param $data
- * @param $pagepath
- * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- public function sendMiniApp($touser, $template_id, $url, $data, $pagepath)
- {
- $app_id = $this->app_id;
- $send_data = [
- 'touser' => $touser,
- 'template_id' => $template_id,
- 'url' => $url,
- 'data' => $data,
- 'miniprogram' => [
- 'appid' => $app_id,
- 'pagepath' => $pagepath,
- ],
- ];
- $result = $this->wechat->template_message->send($send_data);
- \Yii::error('================'.json_encode($send_data));
- if ($this->is_open()) {
- $params = [
- 'mall_id' => $this->mall_id,
- 'user_id' => $this->user_id,
- 'openid' => $this->openid,
- 'send_data' => json_encode($send_data),
- 'result_data' => json_encode($result),
- ];
- WechatSendMessageLog::add($params);
- return $result;
- }
- return $result;
- }
- }
|