1. 程式人生 > >微信使用者掃碼關注,獲取使用者資訊併入庫

微信使用者掃碼關注,獲取使用者資訊併入庫

1.推薦者生成帶引數二維碼,這裡我已經寫過,就不再寫了;寫下獲取access_token

 function __construct()
    {
        $this->appid = config('WXAPP_APPID');
        $this->secrect = config('WXAPP_APPSECRET');
        $this->accessToken = $this->getToken($this->appid,  $this->secrect);
    }
 /**
     * @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 = $this->request_get($url); $token
= json_decode(stripslashes($token)); $arr = json_decode(json_encode($token), true); $access_token = $arr['access_token']; return $access_token; }

2.使用者掃碼事件處理

//獲取使用者關注事件
    public function urlRedirect(){//公眾號配置路徑必須是這裡,接收關注後微信傳過來的引數
        if(!isset($_GET['echostr'
])){ $this->responseMsg(); }else{ $this->valid(); } } public function valid(){ $nonce = $_GET['nonce']; $token = 'FCdVj77fdzdQ771CW6cUvIMipduZ66qw'; $timestamp = $_GET['timestamp']; $echostr = $_GET['echostr']; $signature = $_GET['signature']; //形成陣列,然後按字典序排序 $array = array(); $array = array($nonce, $timestamp, $token); sort($array); //拼接成字串,sha1加密 ,然後與signature進行校驗 $str = sha1( implode( $array ) ); if( $str == $signature ){ //第一次接入weixin api介面的時候 echo $echostr; exit; } } public function responseMsg() { $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 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; } } 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 "請輸入..."; } } public function handleEvent($object) { $contentStr = ""; switch ($object->Event) { case "subscribe": $contentStr = "感謝您關注【好運平臺】"; // $contentStr = "感謝您關注【好運平臺】"."\n".$object->ToUserName."\n".$object->FromUserName."\n".$object->FromUserName."\n".$object->MsgType."\n".$object->Event."\n".$object->EventKey."\n".$object->Ticket; $openid = (string)$object->FromUserName; //資料型別轉換為字串,mmp這個問題找了好久 $refer_id = explode('_',$object->EventKey); //$object->EventKey返回的是qrsence_123這種型別 $this->createuserinfo($openid,$refer_id[1]);//獲取使用者資訊 break; case "SCAN": $contentStr = "您已關注過,謝謝!"; break; } $resultStr = $this->responseText($object, $contentStr); return $resultStr; } 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; }

3.獲取使用者資訊,繫結關係併入庫

//使用者關注後獲取使用者資訊
    public function createuserinfo($openid,$refer_id)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->accessToken . "&openid=" . $openid;
        $user= $this->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
        );
        db('user')->insert($users);
    }

4.部分基礎函式的呼叫

 /**
     * 傳送post請求
     * @param string $url
     * @param string $param
     * @return bool|mixed
     */
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定網頁
        curl_setopt($ch, CURLOPT_HEADER, 0); //設定header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求結果為字串且輸出到螢幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //執行curl
        curl_close($ch);
        return $data;
    }
    /**
     * 傳送get請求
     * @param string $url
     * @return bool|mixed
     */
    function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }