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

$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&app;

$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);