在好例子网,分享、交流、成长!
您当前所在位置:首页PHP 开发实例PHP语言基础 → php通过微信公众号给用户推送自定义模板消息

php通过微信公众号给用户推送自定义模板消息

PHP语言基础

下载此实例
  • 开发语言:PHP
  • 实例大小:4.38KB
  • 下载次数:63
  • 浏览次数:371
  • 发布时间:2019-04-29
  • 实例类别:PHP语言基础
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 微信 php 消息 推送

实例介绍

【实例简介】

【实例截图】

from clipboard

【核心代码】

/===========================API申请地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
define("token", "");//接口配置信息-Token
define("appid", "");//测试号消息-appID
define("appsecret", "");//测试号消息-appsecret
define("template_id", "");//模板消息接口-模版ID
define("openid", "");//管理员openid
//===========================
//===========================API申请地址:http://www.tuling123.com/member/robot/index.jhtml
define("tulingkey", "");//图灵key
//===========================
//===========================API申请地址:https://console.bce.baidu.com/ai/#/ai/ocr/app/list
define("API_Key", "");//百度OCR API_Key
define("Secret_Key", "");//百度OCR Secret_Key
//===========================



$wechat = new wechatcallback();
if (isset($_GET['echostr'])){//微信token验证
	echo $wechat->checkSignature();
}else if(isset($_GET['type'])){//推送消息
	if($_GET['type']=="send"){
		$wechat->send();
	}elseif($_GET['type']=="send2html"){
		$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
		$url = $http_type.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."2html";
		echo '<!DOCTYPE html><html><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>胖虎胖虎胖胖胖胖胖</title><meta name="viewport"content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/><style type="text/css">body{font-family:Helvetica,arial,freesans,clean,sans-serif;font-size:14px;line-height:1.6;color:#333;background-color:#fff;padding:20px;max-width:960px;margin:0 auto}body>*:first-child{margin-top:0!important}body>*:last-child{margin-bottom:0!important}p,blockquote,ul,ol,dl,table,pre{margin:15px 0}h1,h2,h3,h4,h5,h6{margin:20px 0 10px;padding:0;font-weight:bold;-webkit-font-smoothing:antialiased}h1 tt,h1 code,h2 tt,h2 code,h3 tt,h3 code,h4 tt,h4 code,h5 tt,h5 code,h6 tt,h6 code{font-size:inherit}h1{font-size:28px;color:#000}h2{font-size:24px;border-bottom:1px solid#ccc;color:#000}h3{font-size:18px}h4{font-size:16px}h5{font-size:14px}h6{color:#777;font-size:14px}body>h2:first-child,body>h1:first-child,body>h1:first-child h2,body>h3:first-child,body>h4:first-child,body>h5:first-child,body>h6:first-child{margin-top:0;padding-top:0}a:first-child h1,a:first-child h2,a:first-child h3,a:first-child h4,a:first-child h5,a:first-child h6{margin-top:0;padding-top:0}h1 p,h2 p,h3 p,h4 p,h5 p,h6 p{margin-top:10px}a{color:#4183C4;text-decoration:none}a:hover{text-decoration:underline}ul,ol{padding-left:30px}ul li>:first-child,ol li>:first-child,ul li ul:first-of-type,ol li ol:first-of-type,ul li ol:first-of-type,ol li ul:first-of-type{margin-top:0px}ul ul,ul ol,ol ol,ol ul{margin-bottom:0}dl{padding:0}dl dt{font-size:14px;font-weight:bold;font-style:italic;padding:0;margin:15px 0 5px}dl dt:first-child{padding:0}dl dt>:first-child{margin-top:0px}dl dt>:last-child{margin-bottom:0px}dl dd{margin:0 0 15px;padding:0 15px}dl dd>:first-child{margin-top:0px}dl dd>:last-child{margin-bottom:0px}pre,code,tt{font-size:12px;font-family:Consolas,"Liberation Mono",Courier,monospace}code,tt{margin:0 0px;padding:0px 0px;white-space:nowrap;border:1px solid#eaeaea;background-color:#f8f8f8;border-radius:3px}pre>code{margin:0;padding:0;white-space:pre;border:none;background:transparent}pre{background-color:#f8f8f8;border:1px solid#ccc;font-size:13px;line-height:19px;overflow:auto;padding:6px 10px;border-radius:3px}pre code,pre tt{background-color:transparent;border:none}kbd{-moz-border-bottom-colors:none;-moz-border-left-colors:none;-moz-border-right-colors:none;-moz-border-top-colors:none;background-color:#DDDDDD;background-image:linear-gradient(#F1F1F1,#DDDDDD);background-repeat:repeat-x;border-color:#DDDDDD#CCCCCC#CCCCCC#DDDDDD;border-image:none;border-radius:2px 2px 2px 2px;border-style:solid;border-width:1px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;line-height:10px;padding:1px 4px}blockquote{border-left:4px solid#DDD;padding:0 15px;color:#777}blockquote>:first-child{margin-top:0px}blockquote>:last-child{margin-bottom:0px}hr{clear:both;margin:15px 0;height:0px;overflow:hidden;border:none;background:transparent;border-bottom:4px solid#ddd;padding:0}table th{font-weight:bold}table th,table td{border:1px solid#ccc;padding:6px 13px}table tr{border-top:1px solid#ccc;background-color:#fff}table tr:nth-child(2n){background-color:#f8f8f8}img{max-width:100%}</style></head><body><h1>鸡你太美(•̀ᴗ•́)و ̑̑ </h1><hr><h3>这条内容的链接为:</h3><pre><code>'.$url.'</code></pre><h3>这里的链接可以自由设置你的内容,<br>比如下面这样:</h3><p><img src="https://0d077ef9e74d8.cdn.sohucs.com/rp0UNzs"></p><blockquote>https://www.52pojie.cn</blockquote><blockquote>made by 0xE9</blockquote></body></html>';
	}else{
		exit("are you cxk?");
	}
}else{//收到消息
	echo $wechat->responseMsg();
}

class wechatcallback{
	const ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=";
	const SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
	const TULING_URL = "http://www.tuling123.com/openapi/api";
	const BAIDU_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage";
	const BAIDU_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
	
	public function checkSignature(){
		$echoStr = $_GET["echostr"];
		$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 $echoStr;
		}else{
			return;
		}
	}
	
	public function get_access_token(){
		$output = $this->https_request(self::ACCESS_TOKEN_URL .appid."&secret=".appsecret);
		$jsoninfo = json_decode($output, true);
		$access_token = $jsoninfo["access_token"];
		return $access_token;
	}
	
	public function responseMsg(){
		$postStr = @$GLOBALS["HTTP_RAW_POST_DATA"];
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$RX_TYPE = trim($postObj->MsgType);
			if($postObj->FromUserName == openid){
				if($RX_TYPE == "text"){//文本消息
					$contentStr = $this->gettuling($postObj->Content);
					$result = $this->transmitText($postObj, "图灵返回:".$contentStr);
				}else if($RX_TYPE == "image"){//图片消息	
					$contentStr = $this->getocr($postObj->PicUrl);
					$result = $this->transmitText($postObj, "百度识图:".$contentStr);
				}else if($RX_TYPE == "event"){//菜单消息
					$eventkey = $postObj->EventKey;
					if($eventkey==""){$eventkey = $postObj->Event;}
					switch ($eventkey){
						case "subscribe"://普通关注
							$fromuser = $postObj->FromUserName;
							$result = $this->transmitText($postObj, "管理员关注我啦!");
							break;
						case "unsubscribe"://取消关注
							$fromuser = $postObj->FromUserName;
							$content = $this->DeleteUuid($fromuser);
							break;
						default:
							
					}
				}else{
					$result = $this->transmitText($postObj, "未设定的消息:".$RX_TYPE);
				}
			}else{
				$result = $this->transmitText($postObj, "未设置管理员账户");
			}
			return $result;
		}else {
			return;
		}
	}
	
	public function send(){
		$access_token = $this->get_access_token();
		$url = self::SEND_URL . $access_token;
		$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
		$data = [
			'touser' => openid,
			'template_id' => template_id,
			'url' => $http_type.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."2html",//设置推送消息点击后的链接
			'data'=>array(
				'func'=>array('value' => '这是测试来源','color' => '#173177'),
				'time'=>array('value' => date("Y-m-d H:i:s",time()),'color' => '#173177'),
				'msg'=>array('value' => '这是测试内容','color' => '#173177'),
			)
		];
		$json = json_encode($data);
		$req = $this->https_request($url, $json);
		echo $req;
		return $req;
	}
	
	
	private function gettuling($txt){
		$a1=tulingkey;
		if(empty($a1)){
			return "接收的内容为".$txt.",图灵key未配置,无法自动回复";
		}
		$url = self::TULING_URL."?key=".tulingkey."&info=".$txt;
		$res = $this -> https_request($url);
		$res = json_decode($res);
		switch($res ->code){
			case '100000'://文本类消息
				$contentStr = $res->text;
				break;
			case '200000'://链接类
				$contentStr = $res->text;
				$contentStr.= $res->url;
				break;
			default:
				$contentStr = "沙雕网友";
		}
		return $contentStr;
	}
	
	private function getocr($pic){
		$a1=Secret_Key;
		$a2=API_Key;
		if(empty($a1)||empty($a2)){
			return "接收的图片为".$pic.",百度key未配置,无法识别";
		}
		$url = self::BAIDU_URL;
		$data['grant_type'] = 'client_credentials';
		$data['client_id'] = API_Key;
		$data['client_secret'] = Secret_Key;
		$access_token_url = self::BAIDU_TOKEN_URL;
		$result = $this -> https_request($access_token_url, $data);
        $result = json_decode($result,true);
		$access_token = $result['access_token'];
		$request_data = array("url"=>$pic,"detect_direction"=>"true");
        $request_url = $url . "?access_token={$access_token}&aipSdk=php&aipSdkVersion=2_2_2";
		$data_result = $this -> https_request($request_url, $request_data);	
		
		$api = json_decode($data_result,true);
		$str="";
		for($i=0;$i<count($api["words_result"]);$i  ){
			$str.= $api["words_result"][$i]["words"].PHP_EOL;
		}
		return $str;
	}
	
	private function transmitText($object, $content){
		$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
		$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
		return $result;
	}
	
	private function https_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, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
}
?>

标签: 微信 php 消息 推送

实例下载地址

php通过微信公众号给用户推送自定义模板消息

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警