PHP で WeChat パブリック アカウントを開発する方法
#phpWeChat パブリック アカウントの開発方法
1. 関連サーバーの構成
(1) 次のように、独自のサーバー IP ホワイトリストを構成します; (2) 構成時にトークンの構成を開始しますトークンを取得するには、まず、設定を成功させるために、独自の設定のトークン番号を含む既製のコードを独自のサーバーに配置する必要があります。注: 次のコードを構成した後、サーバーからコードを削除したり、index.php の名前を変更したりできます。
#url は、http://118.78.176.74/weixin/index.php
などの完全な URL である必要があります。
<?php /** * wechat php test * update time: 20141008 */ //define your token //下面的即是你设置的token令牌 define("TOKEN", "zj123456"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->valid(); class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if ($this->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->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->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, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if ($tmpStr == $signature) { return true; } else { return false; } } }
コードには 3 つの部分が含まれています。もちろん、次のコードの一部は自動応答ロボットでは使用されません。
#(1)、index.php<?php define("APPID","xxxxxxx"); define("APPSECRET","xxxxxx"); define("TOKEN","zj123456"); require("./wechat.inc.php"); $wechat = new WeChat(APPID,APPSECRET,TOKEN); $wechat->responseMsg(); ?>
(2)、wechat.inc.php
<?php class WeChat { private $_appid; private $_appsecret; private $_token; public function __construct($appid, $appsecret, $token) { $this->_appid = $appid; $this->_appsecret = $appsecret; $this->_token = $token; } /** *_request():发出请求 *@curl:访问的URL *@https:安全访问协议 *@method:请求的方式,默认为get *@data:post方式请求时上传的数据 **/ private function _request($curl, $https = true, $method = 'get', $data = null, $headers = null) { $ch = curl_init(); //初始化 curl_setopt($ch, CURLOPT_URL, $curl); //设置访问的URL // curl_setopt($ch, CURLOPT_HEADER, false); //设置不需要头信息 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只获取页面内容,但不输出 if ($https) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不做服务器认证 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不做客户端认证 } if ($method == 'post') { curl_setopt($ch, CURLOPT_POST, true); //设置请求是POST方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //设置POST请求的数据 } $str = curl_exec($ch); //执行访问,返回结果 curl_close($ch); //关闭curl,释放资源 return $str; } /** *_getAccesstoken():获取access token **/ private function _getAccesstoken() { $file = './accesstoken'; //用于保存access token if (file_exists($file)) { //判断文件是否存在 $content = file_get_contents($file); //获取文件内容 $content = json_decode($content); //json解码 if (time() - filemtime($file) expires_in) //判断文件是否过期 { return $content->access_token; } //返回access token } $content = $this->_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->_appid . "&secret=" . $this->_appsecret); //获取access token的json对象 file_put_contents($file, $content); //保存json对象到指定文件 $content = json_decode($content); //进行json解码 return $content->access_token; //返回access token } /** *_getTicket():获取ticket,用于以后换取二维码 *@expires_secords:二维码有效期(秒) *@type :二维码类型(临时或永久) *@scene:场景编号 **/ public function _getTicket($expires_secords = 604800, $type = "temp", $scene = 1) { if ($type == "temp") { //临时二维码的处理 $data = '{"expire_seconds":' . $expires_secords . ', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //临时二维码生成所需提交数据 return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //发出请求并获得ticket } else { //永久二维码的处理 $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //永久二维码生成所需提交数据 return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //发出请求并获得ticket } } /** *_getQRCode():获取二维码 *@expires_secords:二维码有效期(秒) *@type:二维码类型 *@scene:场景编号 **/ public function _getQRCode($expires_secords, $type, $scene) { $content = json_decode($this->_getTicket($expires_secords, $type, $scene)); //发出请求并获得ticket的json对象 $ticket = $content->ticket; //获取ticket $image = $this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket) ); //发出请求获得二维码图像 //$file = "./".$type.$scene.".jpg";// 可以将生成的二维码保存到本地,便于使用 //file_put_contents($file, $image);//保存二维码 return $image; } public function valid() //检查安全性 { $echoStr = $_GET["echostr"]; //valid signature , option if ($this->checkSignature()) { echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获得用户发送信息 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); switch ($postObj->MsgType) { case 'event': $this->_doEvent($postObj); break; case 'text': $this->_doText($postObj); break; case 'image': $this->_doImage($postObj); break; case 'voice': $this->_doVoice($postObj); break; case 'video': $this->_doVideo($postObj); break; case 'location': $this->_doLocation($postObj); break; default:exit; } } private function _doEvent($postObj) { //事件处理 switch ($postObj->Event) { case 'subscribe': //订阅 $this->_doSubscribe($postObj); break; case 'unsubscribe': //取消订阅 $this->_doUnsubscribe($postObj); break; default:; } } private function _doSubscribe($postObj) { $tpltext = '<xml> <tousername></tousername> <fromusername></fromusername> <createtime>%s</createtime> <msgtype></msgtype> <content></content> </xml>'; $access_token = $this->_getAccesstoken(); $userInfo = $this->getUserinfo($access_token, $postObj->FromUserName); $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '欢迎您关注' . 'Geroge Zhang' . '的世界!'); //还可以保存用户的信息到数据库 echo $str; } private function _doUnsubscribe($postObj) { ; //把用户的信息从数据库中删除 } private function _doText($postObj) { $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <tousername></tousername> <fromusername></fromusername> <createtime>%s</createtime> <msgtype></msgtype> <content></content> <funcflag>0</funcflag> </xml>"; if (!empty($keyword)) { // $data_add = "question=" . $keyword; // $appcode = "2fd264cdc7914b308e51ab986f73fb86"; // $headers = array(); // array_push($headers, "Authorization:APPCODE " . $appcode); // $contentStr = $this->_request("http://jisuznwd.market.alicloudapi.com/iqa/query?question=" . $data_add, false, "GET", '', $headers); $data_add = urlencode($keyword); $contentStr = $this->_request("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" . $data_add, false, "GET", '', ''); $contentStr = json_decode($contentStr, true); if ($contentStr['result'] == 0) { $contentStr = $contentStr['content']; } if ($keyword == "hello") { $contentStr = "你好"; } if ($keyword == "PHP") { $contentStr = "最流行的网页编程语言!"; } if ($keyword == "JAVA") { $contentStr = "较流行的网页编程语言!"; } $msgType = "text"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } exit; } private function _doImage($postObj) { $tpltext = '<xml> <tousername></tousername> <fromusername></fromusername> <createtime>%s</createtime> <msgtype></msgtype> <content></content> </xml>'; $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '您发送的图片在' . $postObj->PicUrl . "。"); echo $str; } 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; } } /** * 获取用户昵称 * @param access_token 前面函数_getAccesstoken已经实现 * @param openid 即FromUserName这个参数 * url $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; * return userInfo */ public function getUserinfo($access_token, $openid) { $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN'; $userInfo = $this->_request($urlid); return $userInfo; } }
注意: ユーザー情報を取得したい場合は、認証されたサブスクリプション アカウントまたはサービス アカウントが必要です。
要約すると、自動応答ロボット機能を実現するには、上記の 3 つのファイルを設定済みのサーバーに配置します。 PHP 関連の知識の詳細については、
PHP 中国語 Web サイトをご覧ください。
以上がPHP で WeChat パブリック アカウントを開発する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









PHP 8.4 では、いくつかの新機能、セキュリティの改善、パフォーマンスの改善が行われ、かなりの量の機能の非推奨と削除が行われています。 このガイドでは、Ubuntu、Debian、またはその派生版に PHP 8.4 をインストールする方法、または PHP 8.4 にアップグレードする方法について説明します。

Visual Studio Code (VS Code とも呼ばれる) は、すべての主要なオペレーティング システムで利用できる無料のソース コード エディター (統合開発環境 (IDE)) です。 多くのプログラミング言語の拡張機能の大規模なコレクションを備えた VS Code は、

あなたが経験豊富な PHP 開発者であれば、すでにそこにいて、すでにそれを行っていると感じているかもしれません。あなたは、運用を達成するために、かなりの数のアプリケーションを開発し、数百万行のコードをデバッグし、大量のスクリプトを微調整してきました。

このチュートリアルでは、PHPを使用してXMLドキュメントを効率的に処理する方法を示しています。 XML(拡張可能なマークアップ言語)は、人間の読みやすさとマシン解析の両方に合わせて設計された多用途のテキストベースのマークアップ言語です。一般的にデータストレージに使用されます

JWTは、JSONに基づくオープン標準であり、主にアイデンティティ認証と情報交換のために、当事者間で情報を安全に送信するために使用されます。 1。JWTは、ヘッダー、ペイロード、署名の3つの部分で構成されています。 2。JWTの実用的な原則には、JWTの生成、JWTの検証、ペイロードの解析という3つのステップが含まれます。 3. PHPでの認証にJWTを使用する場合、JWTを生成および検証でき、ユーザーの役割と許可情報を高度な使用に含めることができます。 4.一般的なエラーには、署名検証障害、トークンの有効期限、およびペイロードが大きくなります。デバッグスキルには、デバッグツールの使用とロギングが含まれます。 5.パフォーマンスの最適化とベストプラクティスには、適切な署名アルゴリズムの使用、有効期間を合理的に設定することが含まれます。

文字列は、文字、数字、シンボルを含む一連の文字です。このチュートリアルでは、さまざまな方法を使用してPHPの特定の文字列内の母音の数を計算する方法を学びます。英語の母音は、a、e、i、o、u、そしてそれらは大文字または小文字である可能性があります。 母音とは何ですか? 母音は、特定の発音を表すアルファベットのある文字です。大文字と小文字など、英語には5つの母音があります。 a、e、i、o、u 例1 入力:string = "tutorialspoint" 出力:6 説明する 文字列「TutorialSpoint」の母音は、u、o、i、a、o、iです。合計で6元があります

静的結合(静的::) PHPで後期静的結合(LSB)を実装し、クラスを定義するのではなく、静的コンテキストで呼び出しクラスを参照できるようにします。 1)解析プロセスは実行時に実行されます。2)継承関係のコールクラスを検索します。3)パフォーマンスオーバーヘッドをもたらす可能性があります。

PHPの魔法の方法は何ですか? PHPの魔法の方法には次のものが含まれます。1。\ _ \ _コンストラクト、オブジェクトの初期化に使用されます。 2。\ _ \ _リソースのクリーンアップに使用される破壊。 3。\ _ \ _呼び出し、存在しないメソッド呼び出しを処理します。 4。\ _ \ _ get、dynamic属性アクセスを実装します。 5。\ _ \ _セット、動的属性設定を実装します。これらの方法は、特定の状況で自動的に呼び出され、コードの柔軟性と効率を向上させます。
