php实现个人微信给自己好友发送消息

<?php
$wx = new wx();
if (!empty($_GET[‘cmd‘]) && $_GET[‘cmd‘] == ‘index‘) {
    //重新扫描登陆时,清空缓存
    session_start();
    unset($_SESSION);
    session_destroy();
    $uuid = $wx->get_uuid();
    $erweima = $wx->qrcode($uuid);
    echo($erweima);//显示二维码
    echo "<a href=‘wx2.php?cmd=login&uuid=" . $uuid . "‘>扫描后,点击登陆确认</a>(备注:扫描后点击登陆按钮" . $uuid . ")";
}

if (!empty($_GET[‘cmd‘]) && $_GET[‘cmd‘] == ‘login‘ && !empty($_GET[‘uuid‘])) {
    //echo $_GET[‘uuid‘];die;
    $loginInfo = $wx->login($_GET[‘uuid‘]);
    if ($loginInfo[‘code‘] == 200) {
        //获取登录成功回调
        $callback = $wx->get_uri($_GET[‘uuid‘]);
        //获取post数据
        $post = $wx->post_self($callback);
        //初始化数据json格式
        $initInfo = $wx->wxinit($post);
        //获取MsgId,参数post,初始化数据initInfo
        //$msgInfo = $wx->wxstatusnotify($post,$initInfo,$callback[‘post_url_header‘]);
        //获取联系人
        $contactInfo = $wx->webwxgetcontact($post, $callback[‘post_url_header‘]);
        //查询的数据放入缓存
        session_start();
        $_SESSION[‘callback_post_url_header‘] = $callback[‘post_url_header‘];
        $_SESSION[‘post‘] = $post;
        $_SESSION[‘initInfo‘] = $initInfo;
        $_SESSION[‘contactInfo‘] = $contactInfo;
        //print_r($_SESSION[‘callback_post_url_header‘]);die;
        header("Location: wx2.php?cmd=send");
        exit;
    }
    //print_r($loginInfo);
    print_r(‘登陆失败‘);
}
if (!empty($_GET[‘cmd‘]) && $_GET[‘cmd‘] == ‘send‘) {
    header("Content-Type: text/html; charset=UTF-8");
    if (!empty($_POST[‘sendText‘])) {
        session_start();

        $callback = $_SESSION[‘callback_post_url_header‘];
        $post = $_SESSION[‘post‘];
        $initInfo = $_SESSION[‘initInfo‘];
        $contactInfo = $_SESSION[‘contactInfo‘];
        //json转数组
        $contactArr = json_decode($contactInfo, true);
        $contactName = anewarray($contactArr[‘MemberList‘], ‘UserName‘);
        //$userName = $contactName[‘文件传输助手‘];//文件助手  :文件传输助手,好友:荳子麻麻
        //发送信息
        //接受消息
        $sendText = $_POST[‘sendText‘];
        $userName = $_POST[‘username‘];
        //print_r($sendText);print_r($userName);die;
        $word = urlencode($sendText);//中文先转码,最后提交的时候在urldecode(json_encode($data));
        $to = $userName;
        if (!empty($sendText)) {
            $sendmsg = $wx->webwxsendmsg($post, $initInfo, $callback, $to, $word);
            // $msg = $word . date("Y-m-d H:i:s") . "\r\n";
            // file_put_contents("logs/log.log", $msg, FILE_APPEND);//记录日志
            header("Location: wx2.php?cmd=send");
        }
    } else {
        session_start();
        $contactInfo = $_SESSION[‘contactInfo‘];
        //json转数组
        $contactArr = json_decode($contactInfo, true);
        $contactName = anewarray($contactArr[‘MemberList‘], ‘UserName‘);

        echo "<form action=‘wx2.php?cmd=send‘ method=‘post‘>";
        echo "<select name = ‘username‘>";
        foreach ($contactName as $k => $v) {
            echo "<option value =" . $v . ">" . $k . "</option>";
        }
        echo "</select>";
        echo "消息: <input type=‘text‘ name=‘sendText‘ id=‘sendText‘>";
        echo "<input type=‘submit‘ value=‘发送‘>";
        echo "</form>";
    }

}

class Wx
{

    function getMillisecond()
    {
        list($t1, $t2) = explode(‘ ‘, microtime());
        return $t2 . ceil(($t1 * 1000));
    }

    private $appid = ‘wx782c26e4c19acffb‘;

    /**
     * 获取唯一的uuid用于生成二维码
     * @return $uuid
     */
    public function get_uuid()
    {
        $url = ‘https://login.weixin.qq.com/jslogin‘;
        $url .= ‘?appid=‘ . $this->appid;
        $url .= ‘&fun=new‘;
        $url .= ‘&lang=zh_CN‘;
        $url .= ‘&_=‘ . time();

        $content = $this->curlPost($url);
        //也可以使用正则匹配
        $content = explode(‘;‘, $content);

        $content_uuid = explode(‘"‘, $content[1]);

        $uuid = $content_uuid[1];
        $this->uuid = $uuid;
        return $uuid;
    }

    /**
     * 生成二维码
     * @param $uuid
     * @return img
     */
    public function qrcode($uuid)
    {
        $url = ‘https://login.weixin.qq.com/qrcode/‘ . $uuid . ‘?t=webwx‘;
        $img = "<img class=‘img‘ src=" . $url . "/>";
        return $img;
    }

    /**
     * 扫描登录
     * @param $uuid
     * @param string $icon
     * @return array code 408:未扫描;201:扫描未登录;200:登录成功; icon:用户头像
     */
    public function login($uuid, $icon = ‘true‘)
    {
        //$url = ‘https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=‘ . $icon . ‘&r=‘ . ~time() . ‘&uuid=‘ . $uuid . ‘&tip=0&_=‘ . getMillisecond();
        $url = ‘https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=‘ . $icon . ‘&r=‘ . ~time() . ‘&uuid=‘ . $uuid . ‘&tip=0&_=‘ . time();
        $content = $this->curlPost($url);
        preg_match(‘/\d+/‘, $content, $match);
        $code = $match[0];
        preg_match(‘/([\‘"])([^\‘"\.]*?)\1/‘, $content, $icon);

        $user_icon = !empty($icon) ? $icon[2] : array();
        if ($user_icon) {
            $data = array(
                ‘code‘ => $code,
                ‘icon‘ => $user_icon,
            );
        } else {
            $data[‘code‘] = $code;
        }
        //echo json_encode($data);//改之前
        return $data;
    }

    /**
     * 登录成功回调
     * @param $uuid
     * @return array $callback
     */
    public function get_uri($uuid)
    {
        $url = ‘https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?uuid=‘ . $uuid . ‘&tip=0&_=e‘ . time();
        $content = $this->curlPost($url);
        $content = explode(‘;‘, $content);
        $content_uri = explode(‘"‘, $content[1]);
        $uri = $content_uri[1];

        preg_match("~^https:?(//([^/?#]*))?~", $uri, $match);
        $https_header = $match[0];
        $_SESSION[‘https_header‘] = $https_header;//补这一句
        $post_url_header = $https_header . "/cgi-bin/mmwebwx-bin";

        $new_uri = explode(‘scan‘, $uri);
        $uri = $new_uri[0] . ‘fun=new&scan=‘ . time();
        $getXML = $this->curlPost($uri);

        $XML = simplexml_load_string($getXML);

        $callback = array(
            ‘post_url_header‘ => $post_url_header,
            ‘Ret‘ => (array)$XML,
        );
        return $callback;
    }

    /**
     * 获取post数据
     * @param array $callback
     * @return object $post
     */
    public function post_self($callback)
    {
        $post = new stdClass();
        $Ret = $callback[‘Ret‘];
        $status = $Ret[‘ret‘];
        if ($status == ‘1203‘) {
            $this->error(‘未知错误,请2小时后重试‘);
        }
        if ($status == ‘0‘) {
            $post->BaseRequest = array(
                ‘Uin‘ => $Ret[‘wxuin‘],
                ‘Sid‘ => $Ret[‘wxsid‘],
                ‘Skey‘ => $Ret[‘skey‘],
                ‘DeviceID‘ => ‘e‘ . rand(10000000, 99999999) . rand(1000000, 9999999),
            );

            $post->skey = $Ret[‘skey‘];

            $post->pass_ticket = $Ret[‘pass_ticket‘];

            $post->sid = $Ret[‘wxsid‘];

            $post->uin = $Ret[‘wxuin‘];

            return $post;
        }
    }

    /**
     * 初始化
     * @param $post
     * @return json $json
     */
    public function wxinit($post)
    {

        $url = $_SESSION[‘https_header‘] . ‘/cgi-bin/mmwebwx-bin/webwxinit?pass_ticket=‘ . $post->pass_ticket . ‘&skey=‘ . $post->skey . ‘&r=‘ . time();

        $post = array(
            ‘BaseRequest‘ => $post->BaseRequest,
        );
        $json = $this->curlPost($url, $post);

        return $json;
    }

    /**
     * 获取MsgId
     * @param $post
     * @param $json
     * @param $post_url_header
     * @return array $data
     */
    public function wxstatusnotify($post, $json, $post_url_header)
    {
        $init = json_decode($json, true);

        $User = $init[‘User‘];
        $url = $post_url_header . ‘/webwxstatusnotify?lang=zh_CN&pass_ticket=‘ . $post->pass_ticket;

        $params = array(
            ‘BaseRequest‘ => $post->BaseRequest,
            "Code" => 3,
            "FromUserName" => $User[‘UserName‘],
            "ToUserName" => $User[‘UserName‘],
            "ClientMsgId" => time()
        );

        $data = $this->curlPost($url, $params);

        $data = json_decode($data, true);

        return $data;
    }

    /**
     * 获取联系人
     * @param $post
     * @param $post_url_header
     * @return array $data
     */
    public function webwxgetcontact($post, $post_url_header)
    {

        $url = $post_url_header . ‘/webwxgetcontact?pass_ticket=‘ . $post->pass_ticket . ‘&seq=0&skey=‘ . $post->skey . ‘&r=‘ . time();

        $params[‘BaseRequest‘] = $post->BaseRequest;

        $data = $this->curlPost($url, $params);

        return $data;
    }

    /**
     * 获取当前活跃群信息
     * @param $post
     * @param $post_url_header
     * @param $group_list 从获取联系人和初始化中获取
     * @return array $data
     */
    public function webwxbatchgetcontact($post, $post_url_header, $group_list)
    {

        $url = $post_url_header . ‘/webwxbatchgetcontact?type=ex&lang=zh_CN&r=‘ . time() . ‘&pass_ticket=‘ . $post->pass_ticket;

        $params[‘BaseRequest‘] = $post->BaseRequest;

        $params[‘Count‘] = count($group_list);

        foreach ($group_list as $key => $value) {
            if ($value[MemberCount] == 0) {
                $params[‘List‘][] = array(
                    ‘UserName‘ => $value[‘UserName‘],
                    ‘ChatRoomId‘ => "",
                );
            }
            $params[‘List‘][] = array(
                ‘UserName‘ => $value[‘UserName‘],
                ‘EncryChatRoomId‘ => "",
            );

        }

        $data = $this->curlPost($url, $params);

        $data = json_decode($data, true);

        return $data;
    }

    /**
     * 心跳检测 0正常;1101失败/登出;2新消息;7不要耍手机了我都收不到消息了;
     * @param $post
     * @param $SyncKey 初始化方法中获取
     * @return array $status
     */
    public function synccheck($post, $SyncKey)
    {
        if (!$SyncKey[‘List‘]) {
            $SyncKey = $_SESSION[‘json‘][‘SyncKey‘];
        }
        foreach ($SyncKey[‘List‘] as $key => $value) {
            if ($key == 1) {
                $SyncKey_value = $value[‘Key‘] . ‘_‘ . $value[‘Val‘];
            } else {
                $SyncKey_value .= ‘|‘ . $value[‘Key‘] . ‘_‘ . $value[‘Val‘];
            }

        }

        $header = array(
            ‘0‘ => ‘https://webpush.wx2.qq.com‘,
            ‘1‘ => ‘https://webpush.wx.qq.com‘,
        );

        foreach ($header as $key => $value) {

            $url = $value . "/cgi-bin/mmwebwx-bin/synccheck?r=" . getMillisecond() . "&skey=" . urlencode($post->skey) . "&sid=" . $post->sid . "&deviceid=" . $post->BaseRequest[‘DeviceID‘] . "&uin=" . $post->uin . "&synckey=" . urlencode($SyncKey_value) . "&_=" . getMillisecond();

            $data[] = $this->curlPost($url);
        }

        foreach ($data as $k => $val) {

            $rule = ‘/window.synccheck={retcode:"(\d+)",selector:"(\d+)"}/‘;

            preg_match($rule, $data[$k], $match);

            if ($match[1] == ‘0‘) {
                $retcode = $match[1];
                $selector = $match[2];
            }
        }

        $status = array(
            ‘ret‘ => $retcode,
            ‘sel‘ => $selector,
        );

        return $status;
    }

    /**
     * 获取最新消息
     * @param $post
     * @param $post_url_header
     * @param $SyncKey
     * @return array $data
     */
    public function webwxsync($post, $post_url_header, $SyncKey)
    {
        $url = $post_url_header . ‘/webwxsync?sid=‘ . $post->sid . ‘&skey=‘ . $post->skey . ‘&pass_ticket=‘ . $post->pass_ticket;

        $params = array(
            ‘BaseRequest‘ => $post->BaseRequest,
            ‘SyncKey‘ => $SyncKey,
            ‘rr‘ => ~time(),
        );
        $data = $this->curlPost($url, $params);

        return $data;
    }

    /**
     * 发送消息
     * @param $post
     * @param $post_url_header
     * @param $to 发送人
     * @param $word
     * @return array $data
     */
    public function webwxsendmsg($post, $json, $post_url_header, $to, $word)
    {

        //header("Content-Type: application/json; charset=UTF-8");
        //header("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        $url = $post_url_header . ‘/webwxsendmsg?pass_ticket=‘ . $post->pass_ticket;

        //$clientMsgId = getMillisecond() * 1000 + rand(1000, 9999);//原方法
        $clientMsgId = time() * 1000 + rand(1000, 9999);//原方法
        $init = json_decode($json, true);
        $User = $init[‘User‘];
        $params = array(
            ‘BaseRequest‘ => $post->BaseRequest,
            ‘Msg‘ => array(
                "Type" => 1,
                "Content" => $word,
                "FromUserName" => $User[‘UserName‘],
                "ToUserName" => $to,
                "LocalID" => $clientMsgId,
                "ClientMsgId" => $clientMsgId
            ),
            ‘Scene‘ => 0,
        );
        $data = $this->curlPost($url, $params, 1);

        return $data;
    }

    /**
     *退出登录
     * @param $post
     * @param $post_url_header
     * @return bool
     */
    public function wxloginout($post, $post_url_header)
    {
        $url = $post_url_header . ‘/webwxlogout?redirect=1&type=1&skey=‘ . urlencode($post->skey);
        $param = array(
            ‘sid‘ => $post->sid,
            ‘uin‘ => $post->uin,
        );
        $this->curlPost($url, $param);

        return true;
    }

    public function curlPost($url, $data = ‘‘, $is_gbk = false, $timeout = 30, $CA = false)
    {
        $cacert = getcwd() . ‘/cacert.pem‘; //CA根证书

        $SSL = substr($url, 0, 8) == "https://" ? true : false;

        //$header = ‘ContentType: application/json; charset=UTF-8‘;
        $header[] = ‘ContentType: application/json;‘;
        $header[] = "charset:UTF-8";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout - 2);
        if ($SSL && $CA) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);   // 只信任CA颁布的证书
            curl_setopt($ch, CURLOPT_CAINFO, $cacert); // CA根证书(用来验证的网站证书是否是CA颁布)
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名,并且是否与提供的主机名匹配
        } else if ($SSL && !$CA) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Expect:‘)); //避免data数据过长问题
        if ($data) {
            if ($is_gbk) {
                $data = urldecode(json_encode($data));

            } else {
                $data = urldecode(json_encode($data));
            }

            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); //data with URLEncode
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }

}

function anewarray($array, $filed = ‘UserName‘, $keyName = ‘NickName‘)
{
    $data = array();
    if (!empty($array)) {
        foreach ($array as $key => $val) {
            if (!empty($val[$filed])) {
                $data[$val[$keyName]] = $val[$filed];
            }
        }
        $data = array_filter($data);
    }

    return $data;
}

  

原文地址:https://www.cnblogs.com/zhangjian816/p/10289277.html

时间: 2024-10-10 11:15:10

php实现个人微信给自己好友发送消息的相关文章

微信企业号开发:主动发送消息

主企业号主动发送消息,也就是企业号主动推送的消息,适合于企业的通知,通告等.因此如果公司有通知,要求通知到所有员工,就应该使用主动发送消息. 格式是json格式,而且微信很灵活,当touser,toparty,totag的json值是null时,微信服务器主动忽略了.原来还担心,如果是null,在生成json格式时如何忽略掉是null的字段. 核心基本类: public class MsgBase { public MsgBase() { this.safe = "0"; //表示是否

关于 使用python向qq好友发送消息(对爬虫的作用----当程序执行完毕或者报错无限给自己qq发送消息,直到关闭)

以前看到网上一些小程序,在处理完事物后会自动发送qq消息,但是一直搞不懂是说明原理.也在网上找过一些python登陆qq发送消息的文字,但是都太复杂了.今天偶然看到一篇文章,是用python调用win32的接口发送qq消息的,觉得不错,就先记录下来,日后肯定会用得上这些小工具. 发送qq消息要求已经登陆qq,而且qq的窗口是独立的,现在新版的qq一般都是将所有的聊天窗口聚合在一起,因此要设置将qq窗口分离,或者将需要发送消息的那个窗口单独分离出来. 上代码吧. # 原理是先将需要发送的文本放到剪

python给qq好友发送消息

步骤 下载Pythoncharm 在pythoncharm里下载pipwin32的扩展(需要适应python版本,我python使用3.7版本) 代码 # 原理是先将需要发送的文本放到剪贴板中,然后将剪贴板内容发送到qq窗口 # 之后模拟按键发送enter键发送消息 import win32gui import win32con import win32clipboard as w import time def get_text(): """获取剪贴板文本"&qu

微信公众平台主动发送消息

该功能利用公众平台客服接口,文档地址: http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html 需要认证公众号方可实现,没有的口可以用测试平台使用. https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=你的access_token 发送图片消息: {     "touser":"ojM5us46feM315cpmf

微信企业号给员工发送消息

先看官方文档 https://work.weixin.qq.com/api/doc#10167/文本消息 请求方式:POST(HTTPS)请求地址: https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN ACCESS_TOKEN 来自: https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=企业号ID&corpsecret=应用secret 见下图:

Swift - 发送消息(文本,图片,文件等)给微信好友或分享到朋友圈

通过调用微信提供的API接口,我们可以很方便的在应用中发送消息给微信好友,或者分享到朋友圈.在微信开发平台(https://open.weixin.qq.com)里,提供了详细的说明文档和样例.但由于提供的样例是使用Objective-C写的,所以这边我写了个Swift版的样例. 1,实现的功能 (1)可以发送各种类型的消息给好友,也可以分享到朋友圈 (2)发送的内容类型包括:纯文本,图片,链接,音乐,视频,gif表情,非gif表情,文件 2,效果图如下       3,注意事项: (1)该样例

友情变“友尽” 微信群发测试好友不靠谱

“好友测试”在七夕佳节掀起了微信圈子里的新一轮狂轰滥炸.针对这种“既愚蠢又野蛮”的病毒式骚扰,无数网友表示“友尽”(友谊走到尽头了),本来没想删的,看到发这个的就马上就删了. “好友测试”到底是否靠谱?它为何在一夜之间“血洗”朋友圈? 崩溃 遭500条测试“突袭” “使用方法,打开微信,设置,通用,功能,群发助手,全选,试下群发 ,看好友还在不.不在的就可以删了!弹出来好友验证就证明对方把你删了,你也删了吧……亲,谢谢你!如有打扰,请见谅!”从上个周末开始,微信上突然出现一条名为“好友测试”的微

给“微信群”发送消息

在微信群里面,"刷屏"的行为是被谴责的.那如果小程硬是要做到"刷屏"的话,有什么办法吗? 显然,靠快速打字是不现实的,用程序来实现才靠谱. 本文介绍如何用程序发送消息到微信群. 参考网页微信的功能,很自然的一个想法就是调用网页微信的接口来实现这个功能. 那么,有没有现成的项目已经实现了对微信接口的封装了呢? itchat,这是一个开源的python项目,封装了微信接口.通过它,可以实现收发消息.分析好友数据等等有兴趣的事情. 所以,小程就用它来实现消息的发送. (1

用python自制微信机器人,定时发送天气预报

0 引言 前段时间找到了一个免费的天气预报API,费了好段时间把这个API解析并组装成自己想用的格式了,就想着如何实现每天发送天气信息给自己.最近无意中发现了wxpy库,用它来做再合适不过了.以下是wxpy库的简介: wxpy基于itchat,使用了 Web 微信的通讯协议,通过大量接口优化提升了模块的易用性,并进行丰富的功能扩展.实现了微信登录.收发消息.搜索好友.数据统计.微信公众号.微信好友.微信群基本信息获取等功能. 废话不多说,代码写起来. 1 环境 操作系统:Windows / Li