Files
kiri-wchat/wchat/base/Template.php
T

156 lines
2.8 KiB
PHP
Raw Normal View History

2020-04-30 22:25:50 +08:00
<?php
namespace wchat\base;
use wchat\common\Miniprogarampage;
use wchat\common\Result;
/**
* Class Template
*/
abstract class Template extends Miniprogarampage
{
private $keywords = [];
private $templateId = '';
private $formId = '';
private $openId = '';
private $page = 'pages/index/index';
private $emphasis_keyword = '';
/**
* @param array $keywords
*/
public function setKeywords(array $keywords)
{
$this->keywords = $keywords;
}
/**
* @param string $templateId
*/
public function setTemplateId(string $templateId)
{
$this->templateId = $templateId;
}
/**
* @param string $formId
*/
public function setFormId(string $formId)
{
$this->formId = $formId;
}
/**
* @param string $openId
*/
public function setOpenId(string $openId)
{
$this->openId = $openId;
}
/**
* @param string $page
*/
public function setPage(string $page)
{
$this->page = $page;
}
/**
* @param string $emphasis_keyword
*/
public function setEmphasisKeyword(string $emphasis_keyword)
{
$this->emphasis_keyword = $emphasis_keyword;
}
/**
* @param $index
* @param $context
* @param $color
*/
public function replaceKeyword($index, $context, $color = '')
{
if (empty($color)) {
$color = '#000';
}
$this->keywords['keyword' . $index] = [
'value' => $context,
'color' => $color
];
}
/**
* @param $color
* @param $context
*/
public function addKeyword($context, $color = null)
{
if (empty($color)) {
$color = '#000';
}
$this->keywords['keyword' . (count($this->keywords) + 1)] = [
'value' => $context,
'color' => $color
];
}
abstract public function getUrl(): string;
/**
* @return Result
* @throws \Exception
*
* 奴隶交易通知
*/
public function sendTemplate()
{
$access_token = $this->config->getAccessToken();
if (empty($access_token)) {
throw new \Exception('request access_token con\'t null.');
}
$url = $this->getUrl() . '?access_token=' . $access_token;
$params = [
"touser" => $this->openId,
"template_id" => $this->templateId,
"page" => $this->page,
"form_id" => $this->formId,
"data" => $this->keywords,
];
if (!empty($this->emphasis_keyword)) {
$params['emphasis_keyword'] = $this->emphasis_keyword;
}
$params = json_encode($params, JSON_UNESCAPED_UNICODE);
$this->request->setIsSSL(true);
2020-05-22 15:17:24 +08:00
$this->request->addHeader('Content-Type', 'application/json');
2020-04-30 22:25:50 +08:00
$this->request->setErrorField('errcode');
$this->request->setErrorMsgField('errmsg');
$result = $this->request->post($url, $params);
$result->append('postBody', $params);
return $this->reset($result);
}
/**
* @param $result
* @return mixed
*/
private function reset($result)
{
$this->openId = '';
$this->keywords = [];
$this->formId = '';
$this->templateId = '';
$this->page = '';
return $result;
}
}