php微信關注公衆號或掃碼實現獲取用戶信息

php微信關注公衆號或掃碼實現獲取用戶信息(內含簡易框架搭建,可複用)

概述

用戶可通過掃描二維碼進行關注或單純進行掃碼操作,實現獲取用戶微信信息,提高公衆號關注率

詳細

流程

掃碼登錄流程圖

準備工作

準備公衆號及配置

本文用測試公衆號進行配置舉例

我的測試賬號

相關接口文檔

獲取access_token

文檔:獲取access_token

生成臨時帶參二維碼

臨時帶參二維碼方式進行生成二維碼,再採用微信事件回調進行用戶信息獲取。
帶參二維碼生成文檔:生成帶參二維碼

用戶事件回調

用戶在進行掃碼或其他事件,微信會進行事件回調。
微信事件回調文檔:微信事件回調

獲取用戶詳細信息

獲取用戶詳細信息:獲取用戶詳細信息

詳細程序實現-僅供參考

<?php

/**
 * Class WechatController
 *
 * @package \\${NAMESPACE}
 */
class WechatController extends BaseController
{
    private $_token = "onepie";
    private $appid = '******';
    private $secrect = '******';
    private $accessToken = '';

    static $qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?";
    static $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
    static $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";

    public function indexAction()
    {
        $fqid = rand(1000000, 99999999);
        $ACCESS_TOKEN = $this->getToken($this->appid, $this->secrect);
        $url = $this->getQrcodeurl($ACCESS_TOKEN, $fqid, 2);
        file_put_contents(LOG_PATH . '/wx.log', $fqid, FILE_APPEND);
        $img_url = $this->DownLoadQr($url, 'qrcode');
        $this->setData('qrcode_url', $img_url);
        $this->setView('index');
    }

    /**
     * 獲取關注二維碼ticket
     * @param     $ACCESS_TOKEN
     * @param     $fqid
     * @param int $type
     *
     * @return bool|string
     */
    protected function getQrcodeurl($ACCESS_TOKEN, $fqid, $type = 1)
    {
        $url = self::$qrcode_url . 'access_token=' . $ACCESS_TOKEN;
        if ($type == 1) {
            //生成永久二維碼
            $qrcode = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_str": ' . $fqid . '}}}';
        } else {
            //生成臨時二維碼
            $qrcode = '{"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": ' . $fqid . '}}}';
        }
        $result = http_post_data($url, $qrcode);
        $oo = json_decode($result[1]);
        if (empty($oo->ticket)) {
            return false;
        }
        if (!$oo->ticket) {
            $this->ErrorLogger('getQrcodeurl falied. Error Info: getQrcodeurl get failed');
            exit();
        }
        $url = self::$qrcode_get_url . 'ticket=' . $oo->ticket . '';
        echo $oo->ticket;
        return $url;
    }

    /**
     * 保存二維碼到服務器
     * 可直接進行展示不進行存儲,看業務需求
     *
     * @param $url
     * @param $filestring
     *
     * @return bool|string
     */
    protected function DownLoadQr($url, $filestring)
    {
        if ($url == "") {
            return false;
        }
        $filename = $filestring . rand(0, 99999999999) . '.jpg';
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
        /*if (!file_exists('/public/qrcode/' . $filename)) {
            touch('/public/qrcode/' . $filename);
        }*/
        $file = PUBLIC_PATH . 'qrcode/' . $filename;
        $fp2 = fopen($file, "a");
        if (fwrite($fp2, $img) === false) {
            $this->ErrorLogger('dolwload image falied. Error Info: 無法寫入圖片');
            exit();
        }
        fclose($fp2);
        return '/public/qrcode/' . $filename;
    }

    /**
     * @param $appid
     * @param $appsecret
     *
     * @return mixed
     * 獲取token
     */
    protected function getToken($appid, $appsecret)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
        $token = request_get($url);
        $token = json_decode(stripslashes($token));
        $arr = json_decode(json_encode($token), true);
        $access_token = $arr['access_token'];
        return $access_token;
    }


    public function serviceAction()
    {
        $this->showPage = false;
        $echoStr = @$_GET["echostr"];
        if (!isset($echoStr)) {
            $this->responseMsg();
        } else {
            $this->valid();
        }
    }

    public function valid()
    {
        $nonce = $_GET['nonce'];
        $token = $this->_token;
        $timestamp = $_GET['timestamp'];
        $echostr = $_GET['echostr'];
        $signature = $_GET['signature'];
        //形成數組,然後按字典序排序
        $array = array($nonce, $timestamp, $token);
        sort($array);
        //拼接成字符串,sha1加密 ,然後與signature進行校驗
        $str = sha1(implode($array));
        if ($str == $signature) {
            echo $echostr;
            exit;
        }
    }

    /**
     * 微信事件推送接收方法
     */
    public function responseMsg()
    {
        $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            // 微信消息類型
            $RX_TYPE = trim($postObj->MsgType);
            switch ($RX_TYPE) {
                case "text":
                    // 文本消息
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    // 事件推送
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: " . $RX_TYPE;
                    break;
            }
            echo $resultStr;
        } else {
            echo "";
            exit;
        }
    }


    /**
     * 微信文本消息
     * @param $postObj
     */
    public function handleText($postObj)
    {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        if (!empty($keyword)) {
            $msgType = "text";
            $contentStr = "歡迎您關注好運平臺!";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        } else {
            echo "請輸入...";
        }
    }

    /**
     * 獲取時間消息並解析相應參數
     * 提供數據簡單推送(自動回覆)
     * @param $object
     *
     * @return string
     */
    public function handleEvent($object)
    {
        $contentStr = "";
        switch ($object->Event) {
            case "subscribe":
                $contentStr = "感謝您關注【測試賬號】";
                $openid = (string)$object->FromUserName; //數據類型轉換爲字符串,mmp這個問題找了好久
                $refer_id = explode('_', $object->EventKey); //$object->EventKey返回的是qrsence_123這種類型
                $this->createuserinfo($openid, $refer_id[1]);//獲取用戶信息
                break;
            case "SCAN":
                $contentStr = "您已關注過,謝謝!";
                $openid = (string)$object->FromUserName; //數據類型轉換爲字符串,mmp這個問題找了好久
                $refer_id = explode('_', $object->EventKey); //$object->EventKey返回的是qrsence_123這種類型
                $this->createuserinfo($openid, $refer_id[0]);//獲取用戶信息
                break;
        }
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }

    /**
     * 消息回覆模板
     * @param     $object
     * @param     $content
     * @param int $flag
     *
     * @return string
     */
    public function responseText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    /**
     * 獲取用戶詳細信息
     * @param $openid
     * @param $refer_id
     */
    public function createuserinfo($openid, $refer_id)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->getToken($this->appid, $this->secrect) . "&openid=" . $openid;
        $user = request_get($url);
        $user = json_decode($user, true);
        $users = array(
            'openid' => $openid,
            'nickname' => $user['nickname'],
            'avatar' => $user['headimgurl'],
            'sex' => $user['sex'],
            'unionid' => $user['unionid'],
            'status' => 1,
            'reg_time' => $user['subscribe_time'],//關注公衆號的時間
            'bind_user' => $refer_id
        );
        $user_str = date('Y-m-d H:i:s') . "\t";
        foreach ($users as $key => $value) {
            $user_str .= $key . '=' . $value . "\t";
        }
        $user_str .= "\n";
        file_put_contents(LOG_PATH . "wx.log", $user_str, FILE_APPEND);
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章