<?php
class WeChat{
private $appid;
private $appsecret;
public function __construct($appid,$appsecret)
{
$this->appid = $appid;
$this->appsecret = $appsecret;
}
public function testSendMsg(){
$openId = 'oVyHG5JWLNN0cSUA7u8GRMIdQo_4';
$tplId = 'HSUANS7YSpm5OuriAZhzTQEjTCHOChaS4o_3UQ7--lY';
$params = [
['thing2'=>['value'=>'订单号']],
['phrase2'=>['value'=>'已维修']],
];
$this->sendTplMsg($openId, $tplId, $params);
}
public function sendTplMsg($openId, $tplId, $params, $page = "") {
$url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $this->getAccessToken();
$data = [];
foreach ($params as $key => $value) {
$data[$key] = $value;
}
$values = [
"touser" => $openId,
"template_id" => $tplId,
"data" => $data,
];
if (!empty($page)) {
$values["page"] = $page;
}
try {
$json = $this->httpRequest($url,'POST',json_encode($values));
$res = json_decode($json,true);
if (!empty($res["errcode"])) {
print $res["errmsg"] . " " . $res["errcode"];
exit();
}
}catch (Exception $e){
print $e->getMessage();
exit();
}
}
public function getAccessToken(){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
$json = $this->httpRequest($url);
$data = json_decode($json, true);
$accessToken = $data['access_token'];
$tokenExpires = time() + 7200;
return $accessToken;
}
public function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false){
$method = strtoupper($method);
$ci = curl_init();
curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ci, CURLOPT_TIMEOUT, 7);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "POST":
curl_setopt($ci, CURLOPT_POST, true);
if (!empty($postfields)) {
$tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
}
break;
default:
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method);
break;
}
$ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
curl_setopt($ci, CURLOPT_URL, $url);
if ($ssl) {
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE);
}
curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ci, CURLOPT_MAXREDIRS, 2);
curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ci, CURLINFO_HEADER_OUT, true);
$response = curl_exec($ci);
$requestinfo = curl_getinfo($ci);
$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
if ($debug) {
echo "=====post data======\r\n";
var_dump($postfields);
echo "=====info===== \r\n";
print_r($requestinfo);
echo "=====response=====\r\n";
print_r($response);
}
curl_close($ci);
return $response;
}
}