PHP前端开发

微信开发系列教程(1)

百变鹏仔 6小时前 #前端问答
文章标签 教程

首先我们需要申请一个微信公众账号,因为这个公众账号是公司的,所以不方便透露给大家! 相信简单的申请工作都是没有问题的!申请成功之后,菜单栏会出现“高级功能”,如下图:

里面有2中模式可以选择,“编辑模式”和“开发模式”,上面都详细的描述就不再想大家作解释了! 

这里我们要讲的是开发模式。好了,到现在为止就可以进入开发模式的讲解了!

然后我们在配置URL和Token值,如下图:

URL:填写我们放demo的访问网址,例如:http://www.123.com/wx_sample.php

Token:这个值可以随便写。

打开文件wx_sample.php,修改下面的内容

define("TOKEN", "weixin"); //修改成自己填写的token

填写之后,就可以提交了!

验证成功之后,我们可以写一个小例子测试一下,如下代码:

<?php /**  * wechat php test  */// define// your// tokendefine("TOKEN", "weixin");$wechatObj = new wechatCallbackapiTest();$wechatObj->responseMsg();class wechatCallbackapiTest {    public function valid() {        $echoStr = $_GET["echostr"];        // valid        // signature        // ,        // option        if($this-&gt;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-&gt;FromUserName;            $toUsername = $postObj-&gt;ToUserName;            $keyword = trim($postObj-&gt;Content);            $time = time();            $textTpl = "<xml>                            <tousername></tousername>                            <fromusername></fromusername>                            <createtime>%s</createtime>                            <msgtype></msgtype>                            <content></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);        $tmpStr = implode($tmpArr);        $tmpStr = sha1($tmpStr);                                          if($tmpStr == $signature) {            return true;        } else {            return false;        }    }}?&gt;

最简单的回复消息完成了!