一、在小程序后台配置参数。
配置的时候会验证服务器,将一下php代码保存放到服务器上就可以通过验证。
二、服务器上的php代码。
<?php
header('Content-type:text');
define("TOKEN", "anranwebtoken");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
$wechatObj->valid();
}else{
$wechatObj->responseMsg();
}
class wechatCallbackapiTest
{
public function valid() //第一次验证服务器用
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
header('content-type:text');
echo $echoStr;
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;
}
}
public function responseMsg()
{
$postStr = file_get_contents('php://input'); //此处推荐使用file_get_contents('php://input')获取后台post过来的数据
if (!empty($postStr) && is_string($postStr)){
$postArr = json_decode($postStr,true);
if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){ //用户发送文本消息
$fromUsername = $postArr['FromUserName']; //发送者openid
$content = '中文'; //输入想要回复
$data=array(
"touser"=>$fromUsername,
"msgtype"=>"text",
"text"=>array("content"=>$content)
);
$json = json_encode($data,JSON_UNESCAPED_UNICODE); //PHP版本5.4以上
$this->post2($json);
}else if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //用户发送图文消息
$fromUsername = $postArr['FromUserName']; //发送者openid
$media_id = ''; //输入想要回复的图片消息的media_id
$data=array(
"touser"=>$fromUsername,
"msgtype"=>"image",
"image"=>array("media_id"=>$media_id)
);
$json = json_encode($data,JSON_UNESCAPED_UNICODE);
$this->post2($json);
}else if($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //用户进入客服
$fromUsername = $postArr['FromUserName']; //用户第一次进入客服系统
$content = '吃了么!';
$data=array(
"touser"=>$fromUsername,
"msgtype"=>"text",
"text"=>array("content"=>$content)
);
$json = json_encode($data,JSON_UNESCAPED_UNICODE);
$this->post2($json);
}else{
exit('error');
}
}else{
exit;
}
}
//获取access_token/* 调用微信api,获取access_token,有效期7200s*/
public function Curl() {
$appid="你自己的appid";
$appsecret="小程序的appsecret";
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret; //替换成自己的小程序id和secret
$result = file_get_contents($url);
$res = json_decode($result,true); //json字符串转数组
return $res['access_token'];
}
//更新access_token存储到数据库并返回数据
public function get_token(){
include("common.inc.php"); //这个是数据库链接信息,我是将token存储到数据库中。你可以根据自身情况修改
$times=time();//当前时间
$sql="select A_ID,A_Token,A_Date from wx_anran_accesstoken order by A_ID desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if($row['A_Date'] < $times){
$token= $this->Curl();
$timestamp=time()+7100;
$sqlu="UPDATE `wx_anran_accesstoken` SET `A_Token`='$token',`A_Date`='$timestamp' WHERE A_ID = '$row[A_ID]' ";
$conn->query($sqlu);
return $token;
}else{//没超过,则从数据库取
return $row['A_Token'];
}
}else{
$timestamp=time()+7100;
$token= $this->Curl();
$sqlin="insert into wx_anran_accesstoken(A_Token,A_Date) values('$token','$timestamp')";
$conn->query($sqlin);
return $token;
}
}
//向客户端发送回复消息
public function post2($data){
$access_token = $this->get_token();
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: text',
'content' => $data
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
return $result;
}
}
?>
心得:
1、其中token的保存方式,我采用的是保存到数据库的方式。需要自己去写这一块。
2、我看网上好多文章都是用curl_init()给小程序post消息数据,不知道为什么我试了很多次都不成功,就换了一种方式。
3、基本思路就是,接收用户发送的消息。返回消息给用户端。中间也遇到很多挫折,我也是一点一点的实验,一点点的找错才完善的。大的框架就是这样,后期我是打算在这个基础上接入聊天机器人自动聊天。