近期在研究微信公众平台的相关内容,介于网上资料不是很充足,本人使用PHP整理了一下,下面贴出具体的代码,有不足希望大神给予补充,小弟不甚感激。目前只实现给指定的fakeid发送消息,更多的功能希望大家一起补充。
1. 请求的http.php
<?php
class http {
private static $instance = NULL;//实例对象
private $host;//地址
private $port = 80;//端口号
private $fp = NULL;//socket链接资源
private $timeout = 120;//socket请求超时时间(s)
private $header = array();//请求头部信息
private $httpVer = 'HTTP/1.0';//请求标准
private $crlf = "\r\n";//请求分隔符
private $accept = "*/*";
private $agent = 'Mozilla/5.0 (Windows NT 6.1; rv:20.0) Gecko/20100101 Firefox/20.0';//伪装浏览器
private $maxLineLength = 4096;//最大行数长度
private $maxLength = 1024;//最大数据长度
private $resultHeader;//返回头部
private $resultData;//返回内容
/**
* 获取实例单例
* @return object
*/
public static function getInstance() {
if (is_null(self::$instance)) {
self::$instance = new http();
}
return self::$instance;
}
/**
* 隐藏构造函数
*/
private function __construct() {
}
/**
* 设置请求头部信息
* @param array $header 请求头部信息数组
*/
public function setHeader($header) {
$this->header = $header;
}
/**
* 发送请求
* @param string $url 请求链接
* @param array $data post请求数据
* @param string $method 请求方法post/get
*/
public function sendRequest($url, $data=array(), $method='post') {
$urlArr = parse_url($url);
if (isset($urlArr['port'])) {
$this->port = $urlArr['port'];
}
switch (strtolower($urlArr['scheme'])) {
case 'http':
$this->host = $urlArr['host'];
break;
case 'https':
$this->host = 'ssl://' . $urlArr['host'];
$this->port = 443;
break;
default:
echo "Error: wrong url!";
exit;
break;
}
$this->connect();
if (strtolower($method) == 'post') {
$method = 'POST';
} else {
$method = 'GET';
}
$path = isset($urlArr['path']) ? $urlArr['path'] : '/';
if (isset($urlArr['query'])) {
$path .= '?' . $urlArr['query'];
}
$httpVer = isset($this->header['httpVer']) ? $this->header['httpVer'] : $this->httpVer;
$headerStr = "{$method} {$path} {$httpVer}{$this->crlf}";
$host = isset($urlArr['port']) ? $urlArr['host'] . ':' . $urlArr['port'] : $urlArr['host'];
$headerStr .= "Host: {$host}{$this->crlf}";
$accept = isset($this->header['Accept']) ? $this->header['Accept'] : $this->accept;
$headerStr .= "Accept: {$accept}{$this->crlf}";
if (isset($this->header['Referer'])) {
$headerStr .= "Referer: {$this->header['Referer']}{$this->crlf}";
}
$agent = isset($this->header['User-Agent']) ? $this->header['User-Agent'] : $this->agent;
$headerStr .= "User-Agent: {$agent}{$this->crlf}";
if (isset($this->header['Cookie'])) {
$headerStr .= "Cookie: {$this->header['Cookie']}{$this->crlf}";
}
$dataLength = 0;
if ($method == 'POST') {
if (!empty($data)) {
$dataStr = http_build_query($data);
$dataLength = strlen($dataStr);
}
$headerStr .= "Content-Type: application/x-www-form-urlencoded{$this->crlf}";
$headerStr .= "Cache-Control: no-cache{$this->crlf}";
$headerStr .= "Pragma: no-cache{$this->crlf}";
$headerStr .= "Content-Length: {$dataLength}{$this->crlf}";
}
$headerStr .= $this->crlf;
if ($dataLength > 0) {
$headerStr .= $dataStr;
}
fwrite($this->fp, $headerStr, strlen($headerStr));
$this->resultHeader = '';
while ($curContent = fgets($this->fp, $this->maxLineLength)) {
if ($curContent == $this->crlf) {
break;
}
$this->resultHeader .= $curContent;
}
$this->resultData = '';
do {
$curContent = fread($this->fp, $this->maxLength);
if (strlen($curContent) == 0) {
break;
}
$this->resultData .= $curContent;
} while(TRUE);
$this->disconnect();
unset($this->fp);
}
/**
* 获取返回的头部信息
* @return string
*/
public function getResultHeader() {
return $this->resultHeader;
}
/**
* 获取返回的数据信息
* @return string
*/
public function getResultData() {
return $this->resultData;
}
/**
* 发起请求
*/
private function connect() {
$this->fp = fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
if (!$this->fp) {
echo "Error: {$errno}--{$errstr}";
exit;
}
}
/**
* 结束请求
*/
private function disconnect() {
return fclose($this->fp);
}
}
?>
2. 测试的test.php
<?php
include './http.php';
// 微信公众账号
$user = "xxxxxxxx";
// 微信公众号登陆密码 MD5加密
$pass = md5(substr('*******', 0, 16));
$obj = new test($user, $pass);
$obj->sendTextMsg(123456, '你好!');
class test {
private $http;//请求实例
private $cookieLog = 'cookie.log';//cookie的保存文件
private $tokenLog = 'token.log';//token的保存文件
private $user;//用户名
private $pass;//密码
/**
* 构造函数
* @param string $user 用户名
* @param string $pass 密码
*/
public function __construct($user, $pass) {
$this->http = http::getInstance();
$this->user = $user;
$this->pass = $pass;
}
/**
* 模拟登陆
*/
private function login() {
$url = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN";
$post = array();
$post["username"] = $this->user;
$post["pwd"] = $this->pass;
$post["imgcode"] = '';
$post["f"] = "json";
$this->http->sendRequest($url, $post);
$data = json_decode($this->http->getResultData(), TRUE);
if (!(isset($data['ErrCode']) && $data['ErrCode'] == 0)) {
echo "登陆失败";
exit;
}
$arr = parse_url($data['ErrMsg']);
$qarr = explode('&', $arr['query']);
$token = '';
foreach ($qarr as $k=>$v) {
$karr = explode("=", $v);
if ($karr[0] == 'token') {
$token = $karr[1];
}
}
$this->write($this->tokenLog, $token);
$cookie = '';
if (preg_match_all("/set\-cookie: (.*) path/i", $this->http->getResultHeader(), $matches)) {
if (isset ($matches[1])) {
foreach ($matches[1] as $k=>$v) {
$cookie .= $v;
}
}
}
$this->write($this->cookieLog, $cookie);
}
/**
* 指定好友发送消息
* @param int $fakeId fakeid
* @param string $content 消息内容
*/
public function sendTextMsg($fakeId, $content) {
$this->checkLogin();
$cookie = $this->read($this->cookieLog);
$token = $this->read($this->tokenLog);
$header = array();
$header['Referer'] = "https://mp.weixin.qq.com/cgi-bin/singlemsgpage?token={$token}&fromfakeid={$fakeId}&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN";
$header['Cookie'] = $cookie;
$this->http->setHeader($header);
$post = array();
$post['token'] = $token;
$post['tofakeid'] = $fakeId;
$post['type'] = 1;
$post['content'] = $content;
$post['ajax'] = 1;
$post['error'] = 'false';
$url = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&lang=zh_CN";
$this->http->sendRequest($url, $post);
$data = json_decode($this->http->getResultData(), TRUE);
if (isset($data['ret']) && $data['ret'] == 0) {
echo '发送成功';
} else {
echo '发送失败';
}
}
/**
* 写文件
* @param string $filename 文件名
* @param string $content 内容
*/
private function write($filename, $content) {
$fp = fopen($filename, 'w');
fwrite($fp, $content);
fclose($fp);
}
/**
* 读取文件内容
* @param string $filename
* @return string
*/
private function read($filename) {
$data = '';
if (file_exists($filename)) {
$fp = fopen($filename, 'r');
$data = fread($fp, filesize($filename));
fclose($fp);
}
return $data;
}
/**
* 校验登陆
* @return boolean true
*/
private function checkLogin() {
$cookie = $this->read($this->cookieLog);
$token = $this->read($this->tokenLog);
$post = array();
$post['token'] = $token;
$post['ajax'] = 1;
$url = 'https://mp.weixin.qq.com/cgi-bin/getnewmsgnum?t=ajax-getmsgnum&lastmsgid=100002402';
$header['Referer'] = "https://mp.weixin.qq.com/cgi-bin/getmessage?t=wxm-message&token={$token}&lang=zh_CN&count=50"; //伪装来源页地址 http_referer
$header['Cookie'] = $cookie;
$this->http->setHeader($header);
$this->http->sendRequest($url, $post);
$data = json_decode($this->http->getResultData(), TRUE);
if (!(isset($data['ret']) && $data['ret'] == 0)) {
$this->login();
}
return TRUE;
}
}
?>