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

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

官方文档地址: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)

相关推荐

  • 微信支付之APIv3

    微信支付之APIv3

  • 微信公众号开发之配置服务器

    入口: 附上官方文档 详情的官方文档里面都有,我这边只写一些自己的理解,欢迎补充 URL: 是开发者用来接收微信消息和事件的接口URL,必须以http://或https://开头,只能是80 和 44 ...

  • 微信服务号校验URL核心代码

    /验证URL        // @param sMsgSignature: 签名串,对应URL参数的msg_signature        // @param sTimeStamp: 时间戳,对应 ...

  • 微信小程序的制作方法步骤和流程

    从运营的角度讲制作,不是从程序的角度讲开发,所以简单明晰,通俗易懂,小白也能按照流程完成制作. 微信小程序制作步骤及流程 1.确定好微信小程序的的定位和目的 如行业,功能,内容,目标用户,目标市场,意 ...

  • “自发自用”分布式光伏项目的开发全流程(收藏)

    地面项目现在基本上是国企央企参与,分布式由于足够分散,参与的大多数是民营企业,分布式由于投资回报更高,这几年发展的很快,本文中的分布式光伏项目是指在工业园区和商业区等建设.采用"自发自用&q ...

  • 仿微信聊天App开发制作经验分享

    APICloud生态 1周前 hi-早上好!今天从官方论坛搬运来一篇开发者仿微信App的经验分享,想要源代码的同学,可以去帖子里问问作者. 作者:川哥哥 帖子链接:https://community. ...

  • 工商业光伏项目开发全流程

    光伏资讯 | PV-info 2020年中国工商业光伏并网5.3GW,2021年工商业光伏预计有8-10GW的并网规模.工商业光伏项目开发看似复杂,其实并不难! 01 前期开发阶段 1-1 寻找项目资 ...

  • 装修公司的流程步骤详解图

    装修,对于一个家庭来说十分重要.同样,对于一家公司来说,也十分重要.一个舒适.温馨的办公环境,不仅能够提升企业员工的工作效率,对于提升企业的形象来说,也有十分积极的影响.而办公室装修其实也是一项很大的 ...

  • 一般渗透测试的流程步骤是什么?网络安全知识

    渗透测试这个事情不是随便拿个工具就可以做了,要了解业务还需要给出解决方案.那么对于网络安全工程来说,工作中的渗透测试的流程是怎样的?渗透测试与入侵有什么区别? 渗透测试与入侵的最大区别? 渗透测试:出 ...

  • 华为内部硬件开发设计流程

    高可靠新能源行业顶尖自媒体 在这里有电力电子.新能源干货.行业发展趋势分析.最新产品介绍.众多技术达人与您分享经验,欢迎关注微信公众号:电力电子技术与新能源(Micro_Grid),论坛:www.21 ...

  • 微信小程序开发和APP开发,前期创业者应该选择那个?

    小程序和APP两者本身没有好坏之分,只是适不适合企业和商家. APP,小程序可以说就是工具,需要的是合适选择什么工具,这个非常重要.对于发展到一定阶段的企业或者前期就有想法和有资本的企业创业者来说,有 ...

  • 微信分销系统开发有几个好处?

    随着移动互联网的发展趋势,越来越多的人会运用空闲时间进行社交卖货,移动电商越来越受重视. 而微信分销在目前应用范围十分广,特别是在突显的提成分红方面,打开了裂变式传播.那么开发微信分销系统有几个好处呢 ...