<?php
namespace utils;
// appid
define('WX_APPID', sysconfig('wechat','web_appid'));
// appsecret
define('WX_APPSECRET', sysconfig('wechat','web_appsecret'));
// 微信授权url get
define('WX_AUTHORIZE_URL', 'https://open.weixin.qq.com/connect/oauth2/authorize');
// 微信access_token url get
define('WX_ACCESS_TOKEN_URL', 'https://api.weixin.qq.com/sns/oauth2/access_token');
// 微信模板消息 url post
define('WX_TEMPLATE_URL', 'https://api.weixin.qq.com/cgi-bin/message/template/send');
// 微信模板消息token url get
define('WX_MESSAGE_TOKEN_URL', 'https://api.weixin.qq.com/cgi-bin/token');
/**
* 微信授权
*/
class WxAuthorize
{
public function getMessageToken()
{
$token = cache('WX_ACCESS_TOKEN');
if (empty($token))
{
$params = [
'grant_type' => 'client_credential',
'appid' => WX_APPID,
'secret' => WX_APPSECRET,
];
$url = WX_MESSAGE_TOKEN_URL . '?' . http_build_query($params);
$response = curlRequest($url, 'get');
if (!is_array($response) && !empty(json_decode($response, true)))
{
$atData = json_decode($response, true);
if (isset($atData['access_token']))
{
$token = $atData['access_token'];
// 留5分钟缓冲时间
$expire = $atData['expires_in']-600;
cache('WX_ACCESS_TOKEN', $token, $expire);
}
}
}
return $token;
}
/**
* 发送模板消息
*/
public function sendMessage($data)
{
$token = $this->getMessageToken();
$log = ['title' => '发送模板消息'];
if (empty($token))
{
$log['info'] = 'token为空';
trace($log, 'error');
return false;
}
$response = [];
try{
$response = curlRequest(WX_TEMPLATE_URL . '?access_token=' . $token, 'post', json_encode($data, JSON_UNESCAPED_UNICODE), 'Content-type: json');
}catch(\Exception $e)
{
$log['message'] = $e->getMessage();
$log['code'] = $e->getCode();
$log['info'] = '请求异常 发送失败';
trace($log, 'error');
return false;
}
$log['data'] = $response;
if (!is_array($response) && !empty(json_decode($response, true)))
{
$status = json_decode($response, true);
if (isset($status['errcode']) && $status['errcode'] == 0)
{
return true;
}
else
{
$log['info'] = 'errcode 不等于0 发送失败';
trace($log, 'error');
}
}
else
{
$log['info'] = '请求错误 发送失败';
trace($log, 'error');
}
return false;
}
/**
* 获取微信授权url
* @param $redirect_uri 回调地址 http/htpps.....
* @param $scope 应用授权作用域 snsapi_base | snsapi_userinfo
* @param $state 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
* @return string
*/
public function getAuthorizeUrl(string $redirect_uri, $scope = 'snsapi_base', $state = '')
{
$params = [
'appid' => WX_APPID,
'redirect_uri' => $redirect_uri,
'response_type' => 'code',
'scope' => $scope,
'state' => $state,
];
$url = WX_AUTHORIZE_URL . '?' . http_build_query($params) . '#wechat_redirect';
return $url;
}
/**
* 获取微信网页授权access_token url
* @param $code 填写第一步获取的code参数
* @return string
*/
public function getAccessTokenUrl(string $code)
{
$params = [
'appid' => WX_APPID,
'secret' => WX_APPSECRET,
'code' => $code,
'grant_type' => 'authorization_code',
];
$url = WX_ACCESS_TOKEN_URL . '?' . http_build_query($params);
return $url;
}
}
curlRequest
if (!function_exists('curlRequest')) {
/**
* 提交数据
* @param string $url 请求Url
* @param string $method 请求方式 注意 get请求需要把参数拼接到url里
* @param array/string $headers Headers信息
* @param array/string $params 请求参数
* @author baiyu
* @return json
*/
function curlRequest($url, $method, $params = [], $headers = ''){
if (is_array($params)) {
$requestString = http_build_query($params);
} else {
$requestString = $params ? : '';
}
if (empty($headers)) {
$headers = array('Content-type: text/json');
} elseif (!is_array($headers)) {
parse_str($headers,$headers);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$method = strtoupper($method);
switch ($method){
case "GET" : curl_setopt($ch, CURLOPT_HTTPGET, 1);break;
case "POST": curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);break;
case "PUT" : curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);break;
case "DELETE": curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);break;
}
$response = curl_exec($ch);
curl_close($ch);
if (stristr($response, 'HTTP 404') || $response == '') {
return array('Error' => '请求错误');
}
return $response;
}
}