您的位置:首页 > 移动开发 > 微信开发

php调用微信客服消息接口给用户发送信息

2017-09-07 17:32 585 查看
$token_file = fopen("token.txt", "r"); //获取文本里的access_token和时间戳
$rs = fgets($token_file);
fclose($token_file);
$attr = explode(',',$rs);
$time2 = time();
$token = $attr[0];
if(intval($time2)-intval($attr[1])>7000) { //判断时间戳是否过期,如果过期就重新调用接口,获取access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=公众号的sppid&secret=公众号的secret";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
$output = json_decode($output, true);
$token_file = fopen("token.txt","w");//打开token.txt文件
fwrite($token_file,$output['access_token'].','.time());//重写tken.txt全部内容
fclose($token_file);//关闭文件流
curl_close($curl);
$token = $output['access_token'];
}

$postdata ='{"touser":"用户的openid","msgtype":"text","text":{"content":"内容"}}';
$opts = array(
'http' => array(
'method' => 'POST',
'Content-Length' => strlen($postdata),
'Host' => 'api.weixin.qq.com',
'Content-Type' => 'application/json',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$token.'', true, $context);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: