在第三方全網發佈的時候出現一個大坑php
記錄一個大坑node
上圖是成功時候的截圖,以前一直返回api消息失敗json
直接上代碼api
public function get_kefu_service($openid, $key) { $access_token = $this->get_authorizer_access_token($key); if (is_array($access_token)) { $key = $access_token ['msg']; } Yii::info("去發送客服消息了access_token:{$access_token} key :{$key}"); $data = [ "touser" => $openid, "msgtype" => 'text', "text" => [ "content" => $key . '_from_api' ] ]; $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token; $postdata = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //改用你的請求方法 $rt = Yii::$app->openwxapp->http_request($url, $postdata); print_r($rt); } public function get_authorizer_access_token($auth_code) { //這裏本身去生成吧 $component_access_token = getComponentAccessToken() $url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" . $component_access_token; $postdata = [ "component_appid" => $appid,//你的第三方appid "authorization_code" => $auth_code ]; $postdata = json_encode($postdata, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //改爲你的post方法 $json = Yii::$app->openwxapp->http_request($url, $postdata); $data = json_decode($json, true); if (isset($data ['errcode']) && $data ['errcode'] != 0) { return [ 'msg' => $data ['errmsg'] ]; } return $data ['authorization_info'] ['authorizer_access_token']; }
接下來就是入口調用我用的是yii2框架,根據你本身的實際狀況獲取參數yii2
$appid = Yii::$app->request->get('appid', 0); $timeStamp = Yii::$app->request->get('timestamp', 0); $nonce = Yii::$app->request->get('nonce'); $encrypt_type = Yii::$app->request->get('encrypt_type'); $msg_sign = Yii::$app->request->get('msg_signature'); $encryptMsg = file_get_contents('php://input'); $oOpenWx = Yii::$app->openwxapp; $pc = new WXBizMsgCrypt($oOpenWx->token, $oOpenWx->encodingAesKey, $oOpenWx->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); $aData = $this->xmlToArray($msg); //判斷消息類型 if (isset($aData['Content'])) { $content = trim($aData['Content']); $toUserName = $aData['ToUserName']; $fromUserName = (string) $aData['FromUserName']; if (preg_match('/^QUERY_AUTH_CODE/', $content) && $toUserName == 'gh_8dad206e9538') { $auth_code = preg_replace('/^QUERY_AUTH_CODE:(.+)/', '$1', $content); $this->get_kefu_service($fromUserName, $auth_code); } }