溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php進(jìn)行微信公眾號開發(fā)的方法

發(fā)布時(shí)間:2020-08-19 15:19:44 來源:億速云 閱讀:297 作者:小新 欄目:編程語言

這篇文章主要介紹了php進(jìn)行微信公眾號開發(fā)的方法,具有一定借鑒價(jià)值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。

php如何進(jìn)行微信公眾號開發(fā)

1、配置相關(guān)服務(wù)器

(1) 如下,把自己的服務(wù)器ip白名單配置上;

(2) 開始配置令牌,配置令牌時(shí)先需要把現(xiàn)成的代碼放到自己的服務(wù)器上面,代碼里面包含自己的設(shè)置的令牌號碼,這樣才可以配置成功。

注意:下面這個(gè)代碼在配置好后,即可從服務(wù)器上面刪除代碼或者把index.php改一個(gè)名字。

url必須是完整的url,比如   http://118.78.176.74/weixin/index.php

php進(jìn)行微信公眾號開發(fā)的方法

php進(jìn)行微信公眾號開發(fā)的方法

<?php
/**
 * wechat php test
 * update time: 20141008
 */

//define your token
//下面的即是你設(shè)置的token令牌

define("TOKEN", "zj123456");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)) {

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $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 = "Welcome to wechat world!";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            } else {
                echo "Input something...";
            }

        } else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }
}

2、配置ok后,接下來就可以實(shí)現(xiàn)相關(guān)的微信公眾號相關(guān)功能,比如說自動回復(fù)機(jī)器人。

代碼包含3部分,當(dāng)然,自動回復(fù)機(jī)器人,下面的代碼有些用不到。

(1) 、index.php

<?php 
define("APPID","xxxxxxx");
define("APPSECRET","xxxxxx");
define("TOKEN","zj123456");

require("./wechat.inc.php");
$wechat = new WeChat(APPID,APPSECRET,TOKEN);
$wechat->responseMsg();
?>

(2)、wechat.inc.php

<?php

class WeChat
{
    private $_appid;
    private $_appsecret;
    private $_token;

    public function __construct($appid, $appsecret, $token)
    {
        $this->_appid = $appid;
        $this->_appsecret = $appsecret;
        $this->_token = $token;
    }

    /**
     *_request():發(fā)出請求
     *@curl:訪問的URL
     *@https:安全訪問協(xié)議
     *@method:請求的方式,默認(rèn)為get
     *@data:post方式請求時(shí)上傳的數(shù)據(jù)
     **/
    private function _request($curl, $https = true, $method = 'get', $data = null, $headers = null)
    {
        $ch = curl_init(); //初始化
        curl_setopt($ch, CURLOPT_URL, $curl); //設(shè)置訪問的URL
        // curl_setopt($ch, CURLOPT_HEADER, false); //設(shè)置不需要頭信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只獲取頁面內(nèi)容,但不輸出
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不做服務(wù)器認(rèn)證
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不做客戶端認(rèn)證
        }
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, true); //設(shè)置請求是POST方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //設(shè)置POST請求的數(shù)據(jù)
        }
        $str = curl_exec($ch); //執(zhí)行訪問,返回結(jié)果
        curl_close($ch); //關(guān)閉curl,釋放資源
        return $str;
    }

    /**
     *_getAccesstoken():獲取access token
     **/
    private function _getAccesstoken()
    {
        $file = './accesstoken'; //用于保存access token
        if (file_exists($file)) { //判斷文件是否存在
            $content = file_get_contents($file); //獲取文件內(nèi)容
            $content = json_decode($content); //json解碼
            if (time() - filemtime($file) < $content->expires_in) //判斷文件是否過期
            {
                return $content->access_token;
            }
//返回access token
        }
        $content = $this->_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->_appid . "&secret=" . $this->_appsecret); //獲取access token的json對象
        file_put_contents($file, $content); //保存json對象到指定文件
        $content = json_decode($content); //進(jìn)行json解碼
        return $content->access_token; //返回access token
    }

    /**
     *_getTicket():獲取ticket,用于以后換取二維碼
     *@expires_secords:二維碼有效期(秒)
     *@type :二維碼類型(臨時(shí)或永久)
     *@scene:場景編號
     **/
    public function _getTicket($expires_secords = 604800, $type = "temp", $scene = 1)
    {
        if ($type == "temp") { //臨時(shí)二維碼的處理
            $data = '{"expire_seconds":' . $expires_secords . ', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //臨時(shí)二維碼生成所需提交數(shù)據(jù)
            return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //發(fā)出請求并獲得ticket
        } else { //永久二維碼的處理
            $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //永久二維碼生成所需提交數(shù)據(jù)
            return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //發(fā)出請求并獲得ticket
        }
    }

    /**
     *_getQRCode():獲取二維碼
     *@expires_secords:二維碼有效期(秒)
     *@type:二維碼類型
     *@scene:場景編號
     **/
    public function _getQRCode($expires_secords, $type, $scene)
    {
        $content = json_decode($this->_getTicket($expires_secords, $type, $scene)); //發(fā)出請求并獲得ticket的json對象
        $ticket = $content->ticket; //獲取ticket
        $image = $this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket)
        ); //發(fā)出請求獲得二維碼圖像
        //$file = "./".$type.$scene.".jpg";// 可以將生成的二維碼保存到本地,便于使用
        //file_put_contents($file, $image);//保存二維碼
        return $image;
    }
    public function valid() //檢查安全性

    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //獲得用戶發(fā)送信息
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        switch ($postObj->MsgType) {
            case 'event':
                $this->_doEvent($postObj);
                break;
            case 'text':
                $this->_doText($postObj);
                break;
            case 'image':
                $this->_doImage($postObj);
                break;
            case 'voice':
                $this->_doVoice($postObj);
                break;
            case 'video':
                $this->_doVideo($postObj);
                break;
            case 'location':
                $this->_doLocation($postObj);
                break;
            default:exit;
        }
    }

    private function _doEvent($postObj)
    { //事件處理
        switch ($postObj->Event) {
            case 'subscribe': //訂閱
                $this->_doSubscribe($postObj);
                break;
            case 'unsubscribe': //取消訂閱
                $this->_doUnsubscribe($postObj);
                break;
            default:;
        }
    }

    private function _doSubscribe($postObj)
    {
        $tpltext = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>';
        $access_token = $this->_getAccesstoken();
        $userInfo = $this->getUserinfo($access_token, $postObj->FromUserName);
        $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '歡迎您關(guān)注' . 'Geroge Zhang' . '的世界!');
        //還可以保存用戶的信息到數(shù)據(jù)庫
        echo $str;

    }

    private function _doUnsubscribe($postObj)
    {
        ; //把用戶的信息從數(shù)據(jù)庫中刪除
    }

    private function _doText($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)) {
            // $data_add = "question=" . $keyword;
            // $appcode = "2fd264cdc7914b308e51ab986f73fb86";
            // $headers = array();
            // array_push($headers, "Authorization:APPCODE " . $appcode);
            // $contentStr = $this->_request("http://jisuznwd.market.alicloudapi.com/iqa/query?question=" . $data_add, false, "GET", '', $headers);
            $data_add = urlencode($keyword);
            $contentStr = $this->_request("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" . $data_add, false, "GET", '', '');
            $contentStr = json_decode($contentStr, true);
            if ($contentStr['result'] == 0) {
                $contentStr = $contentStr['content'];
            }
            if ($keyword == "hello") {
                $contentStr = "你好";
            }

            if ($keyword == "PHP") {
                $contentStr = "最流行的網(wǎng)頁編程語言!";
            }

            if ($keyword == "JAVA") {
                $contentStr = "較流行的網(wǎng)頁編程語言!";
            }

            $msgType = "text";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        }
        exit;
    }

    private function _doImage($postObj)
    {
        $tpltext = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>';
        $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '您發(fā)送的圖片在' . $postObj->PicUrl . "。");
        echo $str;
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 獲取用戶昵稱
     * @param access_token  前面函數(shù)_getAccesstoken已經(jīng)實(shí)現(xiàn)
     * @param openid 即FromUserName這個(gè)參數(shù)
     * url $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
     * return userInfo
     */
    public function getUserinfo($access_token, $openid)
    {
        $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $userInfo = $this->_request($urlid);
        return $userInfo;
    }
}

注意:想要獲取用戶信息必須是認(rèn)證過了的訂閱號或者服務(wù)號!

綜上,把如上三個(gè)文件,放到你的配置的服務(wù)器上面,即可實(shí)現(xiàn)自動回復(fù)機(jī)器人功能。

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享php進(jìn)行微信公眾號開發(fā)的方法內(nèi)容對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問題就找億速云,詳細(xì)的解決方法等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI