微信開放平臺之公衆號第三方平臺探討總結

一、申請地址:https://open.weixin.qq.com/php

二、填寫開發資料:html

 

說明:受權事件接收URL,用於獲取微信服務器每10分鐘推送的ComponentVerifyTicket,該Tikict用於和appid,appscret獲取三方平臺的 component_access_token,而component_access_token 則用於獲取預受權碼pre_auth_code,受權碼換取公衆號的受權信,預受權碼:該API用於使用受權碼換取受權公衆號的受權信息,並換取authorizer_access_tokenauthorizer_refresh_token。 受權碼的獲取,須要在用戶在第三方平臺受權頁中完成受權流程後,在回調URI中經過URL參數提供給第三方平臺方。受權成功會返回受權公衆號的受權信息,值得注意的是,authorizer_refresh_token必須保存好,authorizer_refresh_token是被受權公衆號獲取authorizer_access_token(至關於普通的access_token)的憑證,不然須要從新受權才能獲取。node

三、配置ajax

以下:(注:全部消息收發均要加解密,主動調用的接口不包括)api

public function sysmessage(){
import("@.ORG.aes.WXBizMsgCrypt"); $wxData = $this->weixin_account; $encodingAesKey = $wxData['encodingAesKey']; $token = $wxData['token']; $appId = $wxData['appId']; $timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']) ; $nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']) ; $msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']) ; $encryptMsg = file_get_contents('php://input'); $pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId); $xml_tree = new DOMDocument(); $xml_tree->loadXML($encryptMsg); $array_e = $xml_tree->getElementsByTagName('Encrypt'); $encrypt = $array_e->item(0)->nodeValue; $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>"; $from_xml = sprintf($format, $encrypt); // 第三方收到公衆號平臺發送的消息 $msg = ''; $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg); if ($errCode == 0) { //print("解密後: " . $msg . "\n"); $xml = new DOMDocument(); $xml->loadXML($msg); $array_e = $xml->getElementsByTagName('ComponentVerifyTicket'); $component_verify_ticket = $array_e->item(0)->nodeValue; //logResult('解密後的component_verify_ticket是:'.$component_verify_ticket); $dateline = time(); $date_time = date('Y-m-d H:i:s',time()); $data = array( 'component_verify_ticket'=>$component_verify_ticket, 'token_expires'=>$dateline+600, 'date_time'=>$date_time, ); $res = M('weixin_account')->where(array('appId'=>$this->component_appid))->save($data); if($res) { $weixin_account = M('weixin_account')->where(array('appId'=>$this->component_appid))->find(); S('weixin_account'.$this->component_appid,$weixin_account,600); echo 'success'; } } else { //logResult('解密後失敗:'.$errCode); //$res = M('weixin_account')->where(array('appId'=>$this->component_appid))->save(array('text'=>'fasle')); print($errCode . "\n"); } die(); }

獲取受權跳轉連接:服務器

	//獲取受權回調URL
	public function auth(){
		if (IS_POST) {
			$pre_auth_code = $this->weObj->get_auth_code();		
			$token = $this->weObj->getAccessToken();
			$callback = U('Index/oauth_back','',true,false,true);
			$url = $this->weObj->getRedirect($callback,$pre_auth_code);
			$this->ajaxReturn($url);
		}else {
			$this->ajaxReturn('error');
		}

	}

  

格式:微信

<a href="https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=wx07068eax27ef6eed&pre_auth_code=preauthcode@@@lVMrqq7UdbhIQj1-IwlrtYSXIoIghSSgPrWQmSgzSVChVdQJgJ2iAInQOqURpqFU&redirect_uri=http%3A%2F%2Fsmg.xxx.cn%2Findex.php%3Fg%3DUser%26m%3DIndex%26a%3Doauth_back" id="authurl" style="display: inline;"><img src="https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon_button3_1.png"></a>

  

點擊進行受權:app

再點擊登錄而且受權的時候,會要求用管理員微信掃一掃確認受權。post

受權成功後就獲得被受權公衆號的受權信息了,包括appId,authorizer_access_token,authorizer_refresh_token,頭像,公衆號類型等信息,其中authorizer_refresh_token必須完整保存好。測試

這樣就能夠完成一個公衆號的受權了。

三、處理消息

	//公衆號消息與事件接收URL
//此處爲實例,邏輯須要本身處理,(注意加解密)
	public function eventmsg(){
    	    import("@.ORG.aes.WXBizMsgCrypt");
			$wxData = $this->weixin_account;
			$encodingAesKey = $wxData['encodingAesKey'];
			$token = $wxData['token'];
			$appId = $wxData['appId'];
			$timeStamp  = empty($_GET['timestamp'])     ? ""    : trim($_GET['timestamp']) ;
			$nonce      = empty($_GET['nonce'])     ? ""    : trim($_GET['nonce']) ;
			$msg_sign   = empty($_GET['msg_signature']) ? ""    : trim($_GET['msg_signature']) ;
			
			$encryptMsg = file_get_contents('php://input');
			$pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
			
			$xml_tree = new DOMDocument();
			$xml_tree->loadXML($encryptMsg);
			$array_e = $xml_tree->getElementsByTagName('Encrypt');
			$encrypt = $array_e->item(0)->nodeValue;
			
			
			$format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
			$from_xml = sprintf($format, $encrypt);
                // 第三方收到公衆號平臺發送的消息
			$msg = '';
              $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
			
			if ($errCode == 0) {
					//print("解密後: " . $msg . "\n");
					$xml = new DOMDocument();
					$xml->loadXML($msg);
					
					$array_e = $xml->getElementsByTagName('Content');
					$content = $array_e->item(0)->nodeValue;
				
					$array_e2 = $xml->getElementsByTagName('ToUserName');
					$ToUserName = $array_e2->item(0)->nodeValue;
				
					$array_e3 = $xml->getElementsByTagName('FromUserName');
					$FromUserName = $array_e3->item(0)->nodeValue;
										
					$array_e5 = $xml->getElementsByTagName('MsgType');
					$MsgType = $array_e5->item(0)->nodeValue;
	
					//加密消息
					$encryptMsg = '';
					$text = "<xml>
					<ToUserName><![CDATA[$FromUserName]]></ToUserName>
					<FromUserName><![CDATA[$ToUserName]]></FromUserName>
					<CreateTime>$stime</CreateTime>
					<MsgType><![CDATA[text]]></MsgType>
					<Content><![CDATA[$contentx]]></Content>
					</xml>";
				
					$errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
					echo $encryptMsg;
                        exit();

			
			} else {
				print($errCode . "\n");
				exit();
			}
	}    

  到此受權基本完成了。

 

四、全網發佈檢測

         if ($MsgType=="text") {
                    $needle ='QUERY_AUTH_CODE:'; $tmparray = explode($needle,$content); if(count($tmparray)>1){ //3、模擬粉絲髮送文本消息給專用測試公衆號,第三方平臺方需在5秒內返回空串 //代表暫時不回覆,而後再當即使用客服消息接口發送消息回覆粉絲 $contentx = str_replace ($needle,'',$content); $info = $this->weObj->get_authorization_info($contentx); $test_token = $info['authorizer_access_token']; $content_re = $contentx."_from_api"; echo ''; $data = '{ "touser":"'.$FromUserName.'", "msgtype":"text", "text": { "content":"'.$content_re.'" } }'; $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$test_token; $this->https_post($url, $data); } else{ //2、模擬粉絲髮送文本消息給專用測試公衆號 $contentx = "TESTCOMPONENT_MSG_TYPE_TEXT_callback"; } } //1、模擬粉絲觸發專用測試公衆號的事件 if ($MsgType=="event") { $array_e4 = $xml->getElementsByTagName('Event'); $event = $array_e4->item(0)->nodeValue; $contentx = $event."from_callback"; }

 

效果:

 

檢測

 

成功

到此全網發佈完成

 

相關文章
相關標籤/搜索