php如何进行微信公众号开发-PHP问题

资源魔 27 0

php若何进行微信大众号开发

一、设置装备摆设相干效劳器

(1) 以下,把本人的效劳器ip白名单设置装备摆设上;

(2) 开端设置装备摆设令牌,设置装备摆设令牌时先需求把现成的代码放到本人的效劳器下面,代码外面蕴含本人的设置的令商标码,这样才能够设置装备摆设胜利。

留意:上面这个代码正在设置装备摆设好后,便可从效劳器下面删除了代码或许把index.php改一个名字。

url必需是完好的url,比方 http://118.78.176.74/weixin/index.php

Snipaste_2019-10-19_17-22-06.jpg

Snipaste_2019-10-19_17-22-24.jpg

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

//define your token
//上面的便是你设置的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;
        }
    }
}

二、设置装备摆设ok后,接上去就能够完成相干的微信大众号相干性能,比方说主动回复机械人。

代码蕴含3局部,当然,主动回复机械人,上面的代码有些用没有到。

(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():收回申请
     *@curl:拜访的URL
     *@https:平安拜访协定
     *@method:申请的形式,默许为get
     *@data:post形式申请时上传的数据
     **/
    private function _request($curl, $https = true, $method = 'get', $data = null, $headers = null)
    {
        $ch = curl_init(); //初始化
        curl_setopt($ch, CURLOPT_URL, $curl); //设置拜访的URL
        // curl_setopt($ch, CURLOPT_HEADER, false); //设置没有需求头信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只猎取页面内容,但没有输入
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //没有做效劳器认证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //没有做客户端认证
        }
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, true); //设置申请是POST形式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //设置POST申请的数据
        }
        $str = curl_exec($ch); //执行拜访,前往后果
        curl_close($ch); //封闭curl,开释资本
        return $str;
    }

    /**
     *_getAccesstoken():猎取access token
     **/
    private function _getAccesstoken()
    {
        $file = './accesstoken'; //用于保留access token
        if (file_exists($file)) { //判别文件能否存正在
            $content = file_get_contents($file); //猎取文件内容
            $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); //进行json解码
        return $content->access_token; //前往access token
    }

    /**
     *_getTicket():猎取ticket,用于当前换取二维码
     *@expires_secords:二维码无效期(秒)
     *@type :二维码类型(暂时或永世)
     *@scene:场景编号
     **/
    public function _getTicket($expires_secords = 604800, $type = "temp", $scene = 1)
    {
        if ($type == "temp") { //暂时二维码的解决
            $data = '{"expire_seconds":' . $expires_secords . ', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //暂时二维码天生所需提交数据
            return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //收回申请并取得ticket
        } else { //永世二维码的解决
            $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //永世二维码天生所需提交数据
            return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //收回申请并取得ticket
        }
    }

    /**
     *_getQRCode():猎取二维码
     *@expires_secords:二维码无效期(秒)
     *@type:二维码类型
     *@scene:场景编号
     **/
    public function _getQRCode($expires_secords, $type, $scene)
    {
        $content = json_decode($this->_getTicket($expires_secords, $type, $scene)); //收回申请并取得ticket的json工具
        $ticket = $content->ticket; //猎取ticket
        $image = $this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket)
        ); //收回申请取得二维码图象
        //$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"]; //取得用户发送信息
        $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(), '欢送您存眷' . 'Geroge Zhang' . '的世界!');
        //还能够保留用户的信息到数据库
        echo $str;

    }

    private function _doUnsubscribe($postObj)
    {
        ; //把用户的信息从数据库中删除了
    }

    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 = "最盛行的网页编程言语!";
            }

            if ($keyword == "JAVA") {
                $contentStr = "较盛行的网页编程言语!";
            }

            $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(), '您发送的图片正在' . $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  后面函数_getAccesstoken曾经完成
     * @param openid 即FromUserName这个参数
     * 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;
    }
}

留意:想要猎取用户信息必需是认证过了的定阅号或许效劳号!

综上,把如上三个文件,放到你的设置装备摆设的效劳器下面,便可完成主动回复机械人性能。

更多PHP相干常识,请拜访PHP中文网!

以上就是php若何进行微信大众号开发的具体内容,更多请存眷资源魔其它相干文章!

标签: php php教程 公众号 php故障解决 php使用问题

抱歉,评论功能暂时关闭!