jiaoda
/**
* 获取用户的openid
*
* @param int $uid 用户id
*
* @return mixed|string
*
* @throws ServiceException
*/
public static function getOpenId(int $uid)
{
if (!$user = User::query()->find($uid, [\'token_id\'])) {
throw new ServiceException(\'用户不存在或,openId 为空\');
}
if (!$openid = UserToken::query()->find($user->token_id, [\'miniprogram_token\'])->miniprogram_token ?? \'\') {
throw new ServiceException(\'用户不存在或,openId 为空\');
}
return $openid;
}


/**
* 采纳新品需求消息
* $message = [
* \'uid\' => 用户id
* \'title\' => 商品名称
* \'state\' => 采纳结果
* \'remark\' => 备注
* ]
* @param array $message 发送消息
*
* @throws GuzzleException
*/
public function goodsDemandStatus(array $message)
{
try {
$postData = [
\'touser\' => self::getOpenId($message[\'uid\']), // 小程序openid
\'template_id\' => \'16545\', // 订阅消息id
"page" => "pages/allGreens/allGreens", // 小程序跳转界面,订阅消息跳转界面
\'data\' => [
\'thing1\' => [
\'value\' => $message[\'title\'],
],
\'phrase2\' => [
\'value\' => $message[\'state\'],
],
\'thing3\' => [
\'value\' => $message[\'remark\'],
],
],
];
$response = $this->send($postData);
$re = json_decode($response->getBody()->getContents(), 1);
if (!empty($re[\'errcode\'])) {
Log::channel(\'message\')->info("消息发送失败:" . $re[\'errmsg\']);
}
} catch (\Exception $exception) {
Log::channel(\'message\')->info("消息发送失败:" . $exception->getMessage());
}
}

/**
* 发送订阅消息
*
* @param $data
*
* @return ResponseInterface
*
* @throws GuzzleException
*/
public function send($data)
{
return $this->httpPostJson(\'cgi-bin/message/subscribe/send\', $data);
}

/**
* post 请求
*
* @param string $url 请求uri
* @param array $data 请求参数
*
* @return ResponseInterface
*
* @throws GuzzleException
*/
public function httpPostJson(string $url, array $data = [])
{
$tokenQuery = http_build_query([
\'access_token\' => $this->accessToken
]);

return $this->httpPostJsons($url . "?" . $tokenQuery, $data);
}

/**
* 获取小程序token
*
* @return string
*
* @throws RequestException
* @throws \App\Lib\Vendor\Miniprogram\RequestException
* @throws GuzzleException
*/
public function getToken()
{
// 如果有做缓存,则读取缓存内容
// if ($cache = Cache::get(\'cdy_wx:access_token\')) {
// return $cache;
//}

$re = $this->httpGet("token", [
\'grant_type\' => \'client_credential\',
\'appid\' => $this->appId,
\'secret\' => $this->appSecret,
])->getBody()->getContents();
$response = json_decode($re, true);

if (!empty($response[\'errcode\'])) {
Log::channel(\'store\')->error([
\'getAccessTokenError\' => $response
]);
throw new \App\Lib\Vendor\Miniprogram\RequestException("获取token失败:" . $response["errmsg"]);
}

Cache::put(
\'cdy_wx:access_token\',
$response[\'access_token\'],
now()->addSeconds($response[\'expires_in\'] - 500)
);
return $response[\'access_token\'];
}

/**
* post json 请求
*
* @param string $url 请求uri
* @param array $data 请求参数
*
* @return ResponseInterface
*
* @throws GuzzleException
*/
public function httpPostJsons(string $url, array $data = [])
{
return $this->request($url, \'POST\', [\'json\' => $data, \'verify\' => false]);
}

分类:

技术点:

相关文章: