小程序后台配置:

直接贴代码:
<?php
class Huashishop extends Weixinapi
{
public $appid ='';
public $appSecret ='';
public function index(){
//判断是否为认证
if(isset($_GET['echostr'])){
//如果认证去验证
$this->valid();
}else{
//否则接收客户发送消息
$this->responseMsg();
}
}
//验证前置方法
public function valid()
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
header('content-type:text');
echo $echoStr;
exit;
}else{
echo $echoStr.'+++'.TOKEN;
exit;
}
}
//签名校验
private function checkSignature()
{
//微信加密签名
$signature = $_GET["signature"];
//时间戳
$timestamp = $_GET["timestamp"];
//随机数
$nonce = $_GET["nonce"];
//服务端配置的TOKEN
$token = 'huashishop';
//将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()
{
//接收来自小程序的客户消息JSON
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr) && is_string($postStr)){
//禁止引用外部xml实体
//libxml_disable_entity_loader(true);
//$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$postArr = json_decode($postStr,true);
if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){ //文本消息
$fromUsername = $postArr['FromUserName']; //发送者openid
$toUserName = $postArr['ToUserName']; //小程序id
$textTpl = array(
"ToUserName"=>$fromUsername,
"FromUserName"=>$toUserName,
"CreateTime"=>time(),
"MsgType"=>"transfer_customer_service",
);
exit(json_encode($textTpl));
}elseif(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //图文消息
$fromUsername = $postArr['FromUserName']; //发送者openid
$toUserName = $postArr['ToUserName']; //小程序id
$textTpl = array(
"ToUserName"=>$fromUsername,
"FromUserName"=>$toUserName,
"CreateTime"=>time(),
"MsgType"=>"transfer_customer_service",
);
exit(json_encode($textTpl));
}elseif($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //进入客服动作
$fromUsername = $postArr['FromUserName']; //发送者openid
$content = '您好,如需在线客服,请识别图片二维码添加客服微信,加时备注(商城),谢谢啦~';
$data1=array(
"touser"=>$fromUsername,
"msgtype"=>"text",
"text"=>array("content"=>$content)
);
$data2 = '{
"touser": "'.$fromUsername.'",
"msgtype": "image",
"image": {
"media_id": "iBroHBrc9ONLOh3xvCtxqxLk8mv_NJIXX1Q0Xk3GKs0_ISteVgjjT3Vv4UwY9JTT"
}
}';
$json = json_encode($data1,JSON_UNESCAPED_UNICODE); //php5.4+
$this->sendToUser($data2,'0');
//write_log($json);
$this->sendToUser($json,'1');
}else{
exit('aaa');
}
}else{
echo "";
exit;
}
}
function sendToUser($json,$isend)
{
$access_token = $this->get_accessToken();
/*
* POST发送https请求客服接口api
*/
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
//以'json'格式发送post的https请求
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($json)){
curl_setopt($curl, CURLOPT_POSTFIELDS,$json);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
$output = curl_exec($curl);
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);//捕抓异常
}
curl_close($curl);
if($output == 0 && $isend){
echo 'success';exit;
}
}
/* 调用微信api,获取access_token,有效期7200s -xzz0704 */
/* public function get_accessToken(){
/* 在有效期,直接返回access_token
if(S('access_token')){
return S('access_token');
}
/* 不在有效期,重新发送请求,获取access_token
else{
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6056****&secret=30e46f3ef07b****';
$result = curl_get_https($url);
$res = json_decode($result,true); //json字符串转数组
if($res){
S('access_token',$res['access_token'],7100);
return S('access_token');
}else{
return 'api return error';
}
}
} */
function get_accessToken(&$access_token){
$appid = $this->appid;
$appsecret = $this->appSecret;
$token_file = 'access_token2.json';
$general_token = true;
if(file_exists($token_file) && ($info = json_decode(file_get_contents($token_file)))){
if(time() < $info->create_time + $info->expires_in - 200){
$general_token = false;
$access_token = $info->access_token;
}
}
if($general_token){
$access_token = $this->new_access_token($access_token, $token_file, $appid, $appsecret);
}
return $access_token;
}
function new_access_token(&$access_token, $token_file, $appid, $appsecret){
$token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
$str = file_get_contents($token_url);
$json = json_decode($str);
if(isset($json->access_token)){
$access_token = $json->access_token;
file_put_contents($token_file, json_encode(array('access_token' => $access_token, 'expires_in' => $json->expires_in, 'create_time' => time())));
}else{
file_put_contents('/tmp/error', date('Y-m-d H:i:s').'-Get Access Token Error: '.print_r($json, 1).PHP_EOL, FILE_APPEND);
}
return $access_token;
}
function request($url, $method, array $data, $timeout = 30) {
try {
$ch = curl_init();
/*支持SSL 不验证CA根验证*/
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
/*重定向跟随*/
if (ini_get('open_basedir') == '' && !ini_get('safe_mode')) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
}
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
//设置 CURLINFO_HEADER_OUT 选项之后 curl_getinfo 函数返回的数组将包含 cURL
//请求的 header 信息。而要看到回应的 header 信息可以在 curl_setopt 中设置
//CURLOPT_HEADER 选项为 true
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLINFO_HEADER_OUT, false);
//fail the request if the HTTP code returned is equal to or larger than 400
//curl_setopt($ch, CURLOPT_FAILONERROR, true);
$header = array("Content-Type:application/json;charset=utf-8;", "Connection: keep-alive;");
switch (strtolower($method)) {
case "post":
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_URL, $url);
break;
case "put":
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_URL, $url);
break;
case "delete":
curl_setopt($ch, CURLOPT_URL, $url.'?'.http_build_query($data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
case "get":
curl_setopt($ch, CURLOPT_URL, $url.'?'.http_build_query($data));
break;
case "new_get":
curl_setopt($ch, CURLOPT_URL, $url."?para=".urlencode(json_encode($data)));
break;
default:
throw new Exception('不支持的HTTP方式');
break;
}
$result = curl_exec($ch);
if (curl_errno($ch) > 0) {
throw new Exception(curl_error($ch));
}
curl_close($ch);
return $result;
} catch (Exception $e) {
return "CURL EXCEPTION: ".$e->getMessage();
}
}
public function message(){
$code = $_GET['code'];
$appid='';//';
$appSecret='';//'';
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appSecret.'&js_code='.$code.'&grant_type=authorization_code';
$res = $this->http_request($url);
$res1 = json_decode($res);
$access_token = $this->oauth2_access_token($code);
$this->ajaxReturn(array('data'=>$res1,'access_token'=>$access_token));
}
public function oauth2_access_token($code)
{
$appid='';
$appSecret='';
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appSecret."&code=".$code."&grant_type=authorization_code";
$res = $this->http_request($url);
return json_decode($res, true);
}
protected function http_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}
?>原创文章,转载请标明出处!