分享

关于微信第三方授权开发的流程步骤以及代码

 小马哥技术屋 2021-09-13

做这个,我跟大家是一样的,费尽周折,走了很多坑,所以发出来供大家分享,少走弯路。

官方文档地址:https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/operation/thirdparty/prepare.html

一、创建第三方平台准备工作

二、创建第三方平台

三、第三方平台发布审核成功之后,接下来,我们可以入手代码,直接上代码


$openInfo = [
'token'=>'第三方token','encodingAesKey'=>'第三方encodingAesKey','appId'=>'第三方appid'
];
/*
* 推送component_verify_ticket出于安全考虑,在第三方平台创建审核通过后,微信服务器每隔
* 10分钟会向第三方的消息接收地址推送一次component_verify_ticket,用于获取第三方平台接口
* 调用凭据
*/
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' : // 授权凭证
$componentVerifyTicket = $param['ComponentVerifyTicket'];
Db::name('opens')->where('id', 1)->update(['component_verify_ticket' => $componentVerifyTicket]);
// opens记录第三方开放平台的参数以及后续获取到的口令
logResult('ticket.log', $componentVerifyTicket);
break;
case 'unauthorized' : // 取消授权
break;
case 'authorized' : // 授权
break;
case 'updateauthorized' : // 更新授权
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
// 这里获得的参数:二维码带参数
$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 = '踏奇平台未配置域名,请联系我们';
}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.'">点击链接免费领取</a>';
file_put_contents('content.txt',$contentStr);
}
if (strtolower($param['MsgType']) == 'event'){ //如果是关注subscribe事件
if(strtolower($param['Event'] == 'subscribe')){ // 关注事件
//回复用户消息
$this->responseText($param,$contentStr,$timeStamp,$nonce);
// 执行业务逻辑
$toUser = $param['FromUserName']; // 用户openid
$this->doBusiness($user_id,$fromUser,$toUser); // 处理业务逻辑
}
}else {
file_put_contents('tq-test-event.txt',$postObj->MsgType.','.$postObj->Event);
}
}else {
// 这里是全网发布校验代码块;
// 全网发布文档链接: 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 - 发送事件
$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 = '欢迎关注公众号';
}
}
$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;
}

/*
* 处理接收到的文本内容
*/
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);
}
}

/*
* 回复文本信息
*/
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);
}

/*
*推送客服回复信息
*/
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));
}

/*
* 获取授权 location_report(地理位置上报选项) 0无上报 1进入会话时上报 2每5s上报
* voice_recognize(语音识别开关选项)0关 1开
* customer_service(客服开关选项)0关 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;
}

/*
* 回复消息
*/
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

/*
* 发送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;
}

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约