第三方全网发布 返回Api文本消息解决失败
在第三方全网发布的时候出现一个大坑
记录一个大坑

上图是成功时候的截图,之前一直返回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框架,根据你自己的实际情况获取参数
$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);
}
}
浙公网安备 33010602011771号