做這個,我跟大家是一樣的,費(fèi)盡周折,走了很多坑,所以發(fā)出來供大家分享,少走彎路。 官方文檔地址:https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/operation/thirdparty/prepare.html 一、創(chuàng)建第三方平臺準(zhǔn)備工作 二、創(chuàng)建第三方平臺 三、第三方平臺發(fā)布審核成功之后,接下來,我們可以入手代碼,直接上代碼
$openInfo = [ 'token'=>'第三方token','encodingAesKey'=>'第三方encodingAesKey','appId'=>'第三方appid' ]; /* * 推送component_verify_ticket出于安全考慮,在第三方平臺創(chuàng)建審核通過后,微信服務(wù)器每隔 * 10分鐘會向第三方的消息接收地址推送一次component_verify_ticket,用于獲取第三方平臺接口 * 調(diào)用憑據(jù) */ public function index() { $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'); $xml_tree = new \DOMDocument(); $pc = new WXBizMsgCrypt($this->openInfo['token'], $this->openInfo['encodingAesKey'], $this->openInfo['appId']); $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); logResult('form.log',$from_xml); $msg = ''; $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg); file_put_contents('opens-errcode.txt',$errCode); if ($errCode == 0) { $param = xmlToArray($msg); file_put_contents('index-param.txt',json_encode($param).'|',FILE_APPEND); switch ($param['InfoType']) { case 'component_verify_ticket' : // 授權(quán)憑證 $componentVerifyTicket = $param['ComponentVerifyTicket']; Db::name('opens')->where('id', 1)->update(['component_verify_ticket' => $componentVerifyTicket]); // opens記錄第三方開放平臺的參數(shù)以及后續(xù)獲取到的口令 logResult('ticket.log', $componentVerifyTicket); break; case 'unauthorized' : // 取消授權(quán) break; case 'authorized' : // 授權(quán) break; case 'updateauthorized' : // 更新授權(quán) break; } // $xml = new \DOMDocument(); // $xml->loadXML($msg); // $array_e = $xml->getElementsByTagName('ComponentVerifyTicket'); // $component_verify_ticket = $array_e->item(0)->nodeValue; // Db::name('opens')->where('id', 1)->update(['component_verify_ticket' => $component_verify_ticket]); // logResult('ticket.log', $component_verify_ticket); } echo 'success'; }
/* * 消息與事件接收URL */ public function msg() { $timeStamp = empty ( $_GET ['timestamp'] ) ? "" : trim ($_GET ['timestamp'] ); $nonce = empty ( $_GET ['nonce'] ) ? "" : trim ( $_GET['nonce'] ); $msg_sign = empty ( $_GET ['msg_signature'] ) ? "" : trim( $_GET ['msg_signature'] ); $pc = new WXBizMsgCrypt($this->openInfo['token'], $this->openInfo['encodingAesKey'], $this->openInfo['appId']); //$postArr = $GLOBALS['HTTP_RAW_POST_DATA']; // 7.0不支持 $postArr = file_get_contents("php://input"); $msg = ''; $errCode= $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $postArr,$msg); if($errCode == 0) { $param = xmlToArray($msg); file_put_contents('param.txt',json_encode($param).',',FILE_APPEND); $keyword = isset($param['Content']) ? trim ($param['Content']) : ''; file_put_contents('eventKey.txt',$param['EventKey']); if(isset($param['EventKey']) && !empty($param['EventKey'])) { // qrscene_100 // 這里獲得的參數(shù):二維碼帶參數(shù) $eventKeyArr = explode('_',$param['EventKey']); $user_id = $eventKeyArr[1]; // 品牌商id $userInfo = Db::name('user')->field('url')->where('id',$user_id)->find(); if(empty($userInfo['url'])) { $contentStr = '踏奇平臺未配置域名,請聯(lián)系我們'; }else { $domainUrl = $userInfo['url']; $fromUser = $param['ToUserName']; // 公眾號的原始ID // gans_gzh 是平臺的公眾號信息 $rid = Db::name('fans_gzh')->where('original_id',$fromUser)->value('wechat_appid'); $contentStr = '<a href="'.$domainUrl.$this->url.$rid.'">點擊鏈接免費(fèi)領(lǐng)取</a>'; file_put_contents('content.txt',$contentStr); } if (strtolower($param['MsgType']) == 'event'){ //如果是關(guān)注subscribe事件 if(strtolower($param['Event'] == 'subscribe')){ // 關(guān)注事件 //回復(fù)用戶消息 $this->responseText($param,$contentStr,$timeStamp,$nonce); // 執(zhí)行業(yè)務(wù)邏輯 $toUser = $param['FromUserName']; // 用戶openid $this->doBusiness($user_id,$fromUser,$toUser); // 處理業(yè)務(wù)邏輯 } }else { file_put_contents('tq-test-event.txt',$postObj->MsgType.','.$postObj->Event); } }else { // 這里是全網(wǎng)發(fā)布校驗代碼塊; // 全網(wǎng)發(fā)布文檔鏈接: https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/operation/thirdparty/publish.html if(isset($param['Event']) && $param['ToUserName'] == 'gh_3c884a361561'){ //案例1 - 發(fā)送事件 $contentStr = $param['Event'] . 'from_callback'; }elseif ($keyword == "TESTCOMPONENT_MSG_TYPE_TEXT") { // 案例2 - 返回普通文本 $this->processTextMessage($timeStamp, $nonce, $msg_sign, $keyword, $param['ToUserName'], $param['FromUserName']); } elseif (strpos ($keyword, "QUERY_AUTH_CODE:" ) !== false) { // 返回Api文本信息 $this->processTextMessage($timeStamp, $nonce, $msg_sign, $keyword, $param['ToUserName'], $param['FromUserName']); return 1; }else { $contentStr = '歡迎關(guān)注公眾號'; } } $result = ''; if (!empty ($contentStr )) { $msgCryptObj = new WXBizMsgCrypt($this->openInfo['token'], $this->openInfo['encodingAesKey'], $this->openInfo['appId']); $encryptMsg = ''; $msgCryptObj->encryptMsg($result, $_GET ['timestamp'], $_GET ['nonce'], $encryptMsg); $result = $encryptMsg; } } echo $result; }
/* * 處理接收到的文本內(nèi)容 */ public function processTextMessage($timeStamp, $nonce, $msg_sign, $Content, $toUserName, $fromUserName) { if ('TESTCOMPONENT_MSG_TYPE_TEXT' == $Content) { $text = $Content . '_callback'; $this->replyTextMessage($timeStamp, $nonce, $msg_sign, $text, $toUserName, $fromUserName); } elseif (stristr($Content, "QUERY_AUTH_CODE")) { $textArray = explode(':', $Content); $this->replyApiTextMessage($timeStamp, $nonce, $msg_sign, $textArray[1], $toUserName, $fromUserName); }else{ $this->replyTextMessage($timeStamp, $nonce, $msg_sign, $Content, $toUserName, $fromUserName); } }
/* * 回復(fù)文本信息 */ public function replyTextMessage($timeStamp, $nonce, $msg_sign, $content, $toUserName, $fromUserName) { $pc = new WXBizMsgCrypt($this->openInfo['token'], $this->openInfo['encodingAesKey'], $this->openInfo['appId']); $encryptMsg = ''; $time = time(); $text = "<xml><ToUserName><![CDATA[" . $fromUserName . "]]></ToUserName><FromUserName><![CDATA[" . $toUserName . "]]></FromUserName><CreateTime>" . $timeStamp . "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" . $content . "]]></Content></xml>"; //file_put_contents('11111111.txt', $text); $errCode = $pc->encryptMsg($text, $time, $nonce, $encryptMsg); //file_put_contents('replayCode.txt',$errCode); if ($errCode == 0) { exit($encryptMsg); } else { file_put_contents('replayErrCode.txt', $errCode); exit($errCode); } }
/* * 返回Api文本信息 * @param $timeStamp * @param $nonce * @param $msg_sign * @param $query_auth_code * @param $toUserName * @param $fromUserName */ public function replyApiTextMessage($timeStamp, $nonce, $msg_sign, $query_auth_code, $toUserName, $fromUserName) { $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' . $this->getComponentToken(); $data = [ 'component_appid' => $this->openInfo['appId'], 'authorization_code' => $query_auth_code ]; $res = curl_post($url,$data,true); $getReplyApiTextMessage = json_decode($res,true); $text = $query_auth_code . '_from_api'; $authorizer_access_token = $getReplyApiTextMessage['authorization_info']['authorizer_access_token']; $this->processWxTextMessage($text, $fromUserName, $authorizer_access_token); }
/* *推送客服回復(fù)信息 */ function processWxTextMessage($text, $fromUserName, $authorizer_access_token) { $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $authorizer_access_token; $data = [ 'touser' => $fromUserName, 'msgtype' => 'text', 'text' => ['content' => $text] ]; $res = curl_post($url,$data,true); $getReplyApiTextMessage = json_decode($res,true); file_put_contents('processWechatTextMessage.txt', json_encode($getReplyApiTextMessage)); }
/* * 獲取授權(quán) location_report(地理位置上報選項) 0無上報 1進(jìn)入會話時上報 2每5s上報 * voice_recognize(語音識別開關(guān)選項)0關(guān) 1開 * customer_service(客服開關(guān)選項)0關(guān) 1開 * @param $authorizer_appid * @param $option_name * @param string $option_value * @return string */ function get_authorization($authorizer_appid, $option_name, $option_value = '1') { $arraydata = array( 'location_report', 'voice_recognize', 'customer_service' ); if (in_array($option_name, $arraydata)) { file_put_contents('in_arr.txt',$option_name.','.$authorizer_appid.','.$option_value); $url = 'https://api.weixin.qq.com/cgi-bin/component/api_set_authorizer_option?component_access_token=' . $this->getComponentToken(); $data = [ 'component_appid' => $this->openInfo['appId'], // 開胖平臺appid 'authorizer_appid' => $authorizer_appid, 'option_name' => $option_name, 'option_value' => $option_value ]; $res = curl_post($url,$data,true); file_put_contents('get_authorization-res.txt',$res); $query_authorization = json_decode($res,true); if ($query_authorization->errmsg == 'ok') { return 'ok'; } else { return 'error'; } } else { return 'error'; } }
/* * 請求api獲取令牌 */ public function getComponentToken() { if($this->openInfo['componentAccessTokenTime'] > time()) { $component_access_token = $this->openInfo['component_access_token']; }else { $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'; $data = [ 'component_appid'=>$this->openInfo['appId'], // 第三方平臺 appid 'component_appsecret'=>$this->openInfo["appSecret"], // 第三方平臺 appsecret 'component_verify_ticket'=>$this->openInfo["component_verify_ticket"] // 微信后臺推送的 ticket 令牌 ]; $res = curl_post($url,$data,true); $data = json_decode($res,true); $component_access_token = $data['component_access_token']; $updateData = [ 'componentAccessTokenTime'=>time() + 7100, 'component_access_token'=>$component_access_token ]; if(false === Db::name('opens')->where(['id' => $this->accountId])->update($updateData)) { return false; } } return $component_access_token; }
/* * 回復(fù)消息 */ public function responseText($params,$content,$timeStamp,$nonce) { $template ="<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; $fromUser = $params['ToUserName']; $toUser = $params['FromUserName']; $time = time(); $msgType = 'text'; $res = sprintf($template,$toUser,$fromUser,$time,$msgType,$content); //$pc = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->comm_app_id); $pc = new WXBizMsgCrypt($this->openInfo['token'], $this->openInfo['encodingAesKey'], $this->openInfo['appId']); $encryptMsg = ''; $errCode = $pc->encryptMsg($res,$timeStamp, $nonce, $encryptMsg); file_put_contents('responseTxxt-errcode.txt',$errCode); if($errCode == 0){ $res = $encryptMsg; } echo $res; } WXBizMsgCrypt包地址: 鏈接:https://pan.baidu.com/s/1yogIa9fMXvYS8l6Yv4Z4Gw 提取碼:liol /* * 發(fā)送curl post請求 * @param $url * @return array */ function curl_post($url, $postdata = [], $json = false){ $curl = curl_init(); $this_header = array( "content-type: application/x-www-form-urlencoded;charset=UTF-8" ); curl_setopt($curl,CURLOPT_HTTPHEADER,$this_header); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); if ($postdata){ curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postdata)); } if ($json){ curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postdata,JSON_UNESCAPED_UNICODE)); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); return $result; }
|