当前位置:网站首页>PHP wechat official account development
PHP wechat official account development
2022-07-05 01:17:00 【℡ pure Chinese ~】
Calling interface of official account
/* official account */
public function check_server()
{
// Verify the server address URL If you need to verify for the first time
if (isset($_GET['echostr'])) {
$this->valid();
} else {
// Official operation of official account
$this->responseMsg();
$this->setMenu();
}
}
One 、 Verify official account for the first time
// verification
private function valid()
{
$echoStr = $_GET["echostr"];
if ($this->checkSignature()) {
header('content-type:text');
echo $echoStr;
exit;
} else {
echo $echoStr . '+++' . WXTOKEN;
exit;
}
}
// attestation
private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = WXTOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if ($tmpStr == $signature) {
return true;
} else {
return false;
}
}
Two 、 Official account operation
// Official account automatically replies to messages and pays attention to reply messages
public function responseMsg()
{
//file_get_contents()
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//extract post data
if (!empty($postStr)) {
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//$file = fopen("/var/www/html/ecshop/api/app/ceshi.log", "a+");// Create a file or open a file
// fwrite($file, ' Type of reception ' . '----'.json_encode($postObj).'-------------------' . date('Y-m-d H:i:s', time()) . "\r\n");
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$msgType = $postObj->MsgType; // Message type
$event = $postObj->Event; // Time type ,subscribe( subscribe )、unsubscribe( Unsubscribe )
$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>";
$contentStr = " Default reply text ";
switch ($msgType) {
case "event":
if ($event == "subscribe") {
$contentStr = '<a data-miniprogram-appid=" Applet appid" data-miniprogram-path=" Applet path " data-miniprogram-nickname=" The name of the applet is not required " data-miniprogram-type="text" href=""> Users pay attention to the information returned by official account </a>';
}
break;
case "text":
if (strpos($keyword, ' refund ') !== false || strpos($keyword, ' Refund ') !== false) {
$contentStr = ' The corresponding text is detected and returned ';
// $again = true;
} elseif (strpos($keyword, ' Customer service ') !== false || strpos($keyword, ' complaints ') !== false || strpos($keyword, ' Order ') !== false) {
$contentStr = ' The corresponding text is detected and returned ';
}
break;
}
if ($event == "CLICK" && $postObj->EventKey == "business_cooperation") {
$contentStr = ' Click Customize menu to return ';
}
$msgType = "text";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
} else {
echo "";
exit;
}
}
// Set up custom menus
private function setMenu()
{
$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $this->getToken();
$data = '{ "button":[ { "type":"miniprogram", // Jump applet "name":" Menu name 1", "url":" Alternate address ", "appid":" Applet appid", "pagepath":" Applet page address " }, { "type":"miniprogram", // Jump applet "name":" Menu name 2", "url":" Alternate address ", "appid":" Applet appid", "pagepath":" Applet page address " }, { "type":"click", // Click reply "name":" Menu name 3", "key":"business_cooperation" // Received when replying to the message KEY Customize } ] }';
$resArr = $this->httpRequest($url, $data);
var_dump($resArr);
}
// obtain token
public function getToken($type = 0)
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=appSecret";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
return $access_token;
}
// Request an excuse
private function httpGet($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
private function httpRequest($url, $data = null)
{
$ch = curl_init();
//3. Set parameters
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip Certificate Validation
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Check... From the certificate SSL Whether the encryption algorithm exists
//4. Call interface
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$res = curl_exec($ch);
if (substr($res, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $res = substr($res, 3);
$resArr = json_decode($res, true);
//5. close curl
curl_close($ch);
return $resArr;
}
Official account technology talk
边栏推荐
- [wave modeling 1] theoretical analysis and MATLAB simulation of wave modeling
- Poap: the adoption entrance of NFT?
- Robley's global and Chinese markets 2022-2028: technology, participants, trends, market size and share Research Report
- 26.2 billion! These universities in Guangdong Province have received heavy support
- 【海浪建模2】三维海浪建模以及海浪发电机建模matlab仿真
- [untitled]
- Global and Chinese markets for stratospheric UAV payloads 2022-2028: Research Report on technology, participants, trends, market size and share
- Discrete mathematics: propositional symbolization of predicate logic
- 每日刷题记录 (十三)
- [flutter topic] 64 illustration basic textfield text input box (I) # yyds dry goods inventory #
猜你喜欢
What if the programmer's SQL data script coding ability is weak and Bi can't do it?
SAP UI5 应用开发教程之一百零七 - SAP UI5 OverflowToolbar 容器控件介绍的试读版
JS implementation determines whether the point is within the polygon range
Yyds dry goods inventory kubernetes management business configuration methods? (08)
Take you ten days to easily complete the go micro service series (IX. link tracking)
Yyds dry goods inventory [Gan Di's one week summary: the most complete and detailed in the whole network]; detailed explanation of MySQL index data structure and index optimization; remember collectio
The performance of major mainstream programming languages is PK, and the results are unexpected
微信小程序:微群人脉微信小程序源码下载全新社群系统优化版支持代理会员系统功能超高收益
Armv8-a programming guide MMU (3)
Wechat applet; Gibberish generator
随机推荐
Research Report on the overall scale, major producers, major regions, products and application segmentation of agricultural automatic steering system in the global market in 2022
[wave modeling 1] theoretical analysis and MATLAB simulation of wave modeling
Mongodb series learning notes tutorial summary
Discrete mathematics: Main Normal Form (main disjunctive normal form, main conjunctive normal form)
Delaying wages to force people to leave, and the layoffs of small Internet companies are a little too much!
107. SAP UI5 OverflowToolbar 容器控件以及 resize 事件处理的一些细节介绍
Remote control service
Hedhat firewall
142. Circular linked list II
C basic knowledge review (Part 3 of 4)
The server time zone value ‘� й ��� ʱ 'is unrecognized or representatives more than one time zone【
Are you still writing the TS type code
Arbitrum:二维费用
node工程中package.json文件作用是什么?里面的^尖括号和~波浪号是什么意思?
Wechat applet: exclusive applet version of the whole network, independent wechat community contacts
Compare whether two lists are equal
Innovation leads the direction. Huawei Smart Life launches new products in the whole scene
【海浪建模1】海浪建模的理论分析和matlab仿真
[Chongqing Guangdong education] National Open University spring 2019 1042 international economic law reference questions
Classification of performance tests (learning summary)