微信第三方平台开发详解——PHP版

微信第三方平台开发详解之申请以及全网发布流程

微信第三方平台开发详解之授权流程

微信第三方平台开发详解之代小程序开发

 

补上上一章的刷新授权AccessToken的方法:

  /**
     * 获取小程序的接口调用凭据和授权信息
     * @access public
     *
     */
    public function getAuthorizeInfo($companyId)
    {
        $returnArray = array();
        if($companyId){
            //判断是否存在这个公司的授权信息
            $existInfo = self::get(array('company_id'=>$companyId));
            if($existInfo){
                $existInfo = $existInfo->toArray();
                //判断校验时间戳是否已经小于当前时间戳
                if((time() - $existInfo['check_time']) > -180){
                    //是,更新AccessToken
                    $result = self::updateAuthorize($existInfo['authorizer_appid'], $existInfo['authorizer_refresh_token']);
                    $returnArray = $result;
                }else{
                    //否,直接返回AccessToken信息
                    $returnArray = array(
                        'code' => 1,
                        'info' => $existInfo
                    );
                }
            }
        }else{
            $returnArray = array(
                'code' => 0,
                'info' => '$companyId无效'
            );
        }
        
        return $returnArray;
    }

 

updateAuthorize()方法  

/**
     * 获取小程序的接口调用凭据和授权信息
     * @param $authorizerAppid 授权小程序appid
     * @param $authorizerRefreshToken 接口调用凭据刷新令牌(在授权的公众号具备API权限时,才有此返回值),刷新令牌主要用于第三方平台获取和刷新已授权用户的access_token,只会在授权时刻提供,请妥善保存。 一旦丢失,只能让用户重新授权,才能再次拿到新的刷新令牌
     * @access public
     *
     */
    public function updateAuthorize($authorizerAppid, $authorizerRefreshToken)
    {
        $returnArray = array();
        if($authorizerAppid && $authorizerRefreshToken){
            $wxAccessTokenModel = new \app\diuber\model\WxAccessToken();
            //获取ComponentAccessToken
            $componentAccessTokenRow = $wxAccessTokenModel->getComponentAccessToken();
            
            if($componentAccessTokenRow['code'] == 1){
                $componentAccessToken = $componentAccessTokenRow['info']['access_token'];
                
                $row = json_encode(array(
                    'component_appid' => $this->appid,  //第三方appid
                    'authorizer_appid' => $authorizerAppid, //授权小程序appid
                    'authorizer_refresh_token' => $authorizerRefreshToken   //接口调用凭据刷新令牌
                ));
                $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$componentAccessToken;
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $row);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $output = curl_exec($ch);
                curl_close($ch);
                $output = json_decode($output, true);
                
                //当code=61003表示授权小程序已经主动取消授权,更新第三方小程序授权账号信息
                if(!empty($output['errcode']) && $output['errcode'] == 61003){
                    $existAuthorize = self::get(array('authorizer_appid'=>$authorizerAppid));
                    if($existAuthorize){
                        self::update(array('company_id'=>0,'update_time' => date('Y-m-d H:i:s')),array('authorizer_appid'=>$authorizerAppid));
                    }
                }
                //正常获取刷新后的AccessToken以及新的刷新令牌,更新第三方小程序授权账号信息
                if(!empty($output['authorizer_access_token']) && !empty($output['expires_in']) && !empty($output['authorizer_refresh_token'])){
                    $data = array(
                        'authorizer_access_token' => $output['authorizer_access_token'],
                        'authorizer_refresh_token' => $output['authorizer_refresh_token'],
                        'check_time' => (time() + $output['expires_in']),
                        'update_time' => date('Y-m-d H:i:s')
                    );
                    $result = self::update($data,array('authorizer_appid'=>$authorizerAppid));
                    if($result){
                        $returnArray = array(
                            'code' => 1,
                            'info' => $data
                        );
                    }
                }else{
                    $returnArray = array(
                        'code' => 0,
                        'info' => '刷新authorizer_token失败'
                    );
                }
            }else{
                $returnArray = array(
                    'code' => 0,
                    'info' => '获取component_access_token失败'
                );
            }
        }else{
            $returnArray = array(
                'code' => 0,
                'info' => '参数无效'
            );
        }
        
        return $returnArray;
    }

到这里获取授权AccessToken以及自动刷新授权AccessToken功能就完善了。

 

代小程序业务之修改服务器地址

这里博主被坑了很久第三方小程序上传好代码后,真机上只有打开vconsole的时候才能调通接口,关闭vsonsole就不能调接口了,后来才发现需要把第三方小程序的服务器地址改为自己的服务器地址,不然第三方小程序不能调用自己服务器上的接口。

 

/**
     * 修改服务器地址
     * @access public
     *
     */
    public function modifyDomain()
    {
        $result = '';
        $retrunCode = 0;
        $wxAuthorizerModel = new \app\diuber\model\WxAuthorizer();
        //获取授权AccessToken
        $authorizer = $wxAuthorizerModel->getAuthorizeInfo($this->companyId);
        if(!empty($authorizer) && $authorizer['code'] == 1){
            $url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token='.$authorizer['info']['authorizer_access_token'];
            $data = ' {
                    "action":"add",
                    "requestdomain":["https://xx.xxxx.com"],
                    "wsrequestdomain":["https://gc.diuber.com"],
                    "uploaddomain":["https://xx.xxxx.com"],
                    "downloaddomain":["https://xx.xxxx.com"]
                       }
                    ';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $result = curl_exec($ch);
            curl_close($ch);
            
            $result = json_decode($result, true);
            //errcode=0是添加成功,errcode=85017是添加相同的服务器地址没有变化
            if(isset($result['errcode']) && $result['errcode'] == 0 || $result['errcode'] == 85017){
                $retrunCode = 1;
            }
        }


        return $retrunCode;
    }

 

代小程序业务之为授权的小程序帐号上传小程序代码:

这里需要注意的是在$extJson中我添加了一个第三方平台自定义字段company_id,来区分各个公司下的授权小程序(小程序通过wx.getExtConfig(OBJECT)来获取第三方平台自定义字段:https://mp.weixin.qq.com/debug/wxadoc/dev/api/ext-api.html#wxgetextconfigobject)。如果不需要区分账号就不用写入自定义字段

/**
     * 为授权的小程序帐号上传小程序代码
     * @access public
     */
    public function commitCode()
    {
        $result = '';
        $retrunCode = 0;
        $wxAuthorizerModel = new \app\diuber\model\WxAuthorizer();
        $adminSettingModel = new \app\diuber\model\AdminSetting();
        //获取后台配置的小程序模板编号
        $wxMiniInfo = $adminSettingModel->get(1)->toArray();
        //获取授权AccessToken
        $authorizer = $wxAuthorizerModel->getAuthorizeInfo($this->companyId);
        if(!empty($authorizer) && $authorizer['code'] == 1){
            $url = 'https://api.weixin.qq.com/wxa/commit?access_token='.$authorizer['info']['authorizer_access_token'];
            //$extJson可以从小程序根目录下的app.json获取
            $extJson = '{
                          "ext": {
                            "company_id": "'.$this->companyId.'"
                          },

                          "pages":[
                            "pages/index/index",
                            "pages/personal/personal",
                            "pages/DiYou/DiYou",
                            "pages/Soliciting/Soliciting",
                            "pages/SolicitingOrders/SolicitingOrders",
                            "pages/Service/Service",
                            "pages/Process/Process",
                            "pages/Query/Query",
                            "pages/goPay/goPay",
                            "pages/SearchMore/SearchMore",
                            "pages/carType/carType",
                            "pages/Renting/Renting",
                            "pages/ShowCar/ShowCar",
                            "pages/beforeorde/beforeorde",
                            "pages/Order/Order",
                            "pages/formulate/formulate",
                            "pages/MyFriend/MyFriend",
                            "pages/Wallet/Wallet",
                            "pages/activity/activity",
                            "pages/MyVip/MyVip",
                            "pages/Mycard/Mycard"
                          ],
                          "window":{
                            "backgroundTextStyle":"light",
                            "navigationBarBackgroundColor": "#fff",
                            "navigationBarTitleText": "WeChat",
                            "navigationBarTextStyle":"black"
                          },
                          "tabBar": {
                            "list": [
                              {
                                "pagePath": "pages/index/index",
                                "text": "首页",
                                "iconPath": "images/tabBar/index1.png",
                                "selectedIconPath": "images/tabBar/index.png"
                              },
                              {
                                "pagePath": "pages/Renting/Renting",
                                "text": "车辆",
                                "iconPath": "images/tabBar/lease1.png",
                                "selectedIconPath": "images/tabBar/lease.png"
                              },
                              {
                                "pagePath": "pages/personal/personal",
                                "text": "我的",
                                "iconPath": "images/tabBar/personal1.png",
                                "selectedIconPath": "images/tabBar/personal.png"
                              }
                            ],
                            "color": "#000",
                            "selectedColor": "#48c23d"
                          }
                        }';
            $data = json_encode(array(
                'template_id' => $wxMiniInfo['mini_app_code_template'], //后台配置的小程序的模板编号
                'ext_json' => $extJson,
                'user_version' => $wxMiniInfo['mini_app_version'],  //后台配置的小程序的版本号
                'user_desc' => $wxMiniInfo['mini_app_comment']  //后台配置的小程序的版本描述
            ));
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $result = curl_exec($ch);
            curl_close($ch);
            
            $result = json_decode($result, true);
        }
        
        if(isset($result['errcode']) && $result['errcode'] == 0){
            $retrunCode = 1;
        }
        return $retrunCode;
    }

 

 

代小程序业务之获取体验小程序的体验二维码:

这里需要注意一下接口返回的是二进制编码,需要自己转成图片,我用的是阿里云的oss保存图片,所以就不贴uploadImageBinaryAction的代码了,并且我这边return的是图片记录的编号,到curl结束后面你们可以自己写了。注:体验二维码图片是不会变的,所以后面重新提交代码的话也不用重新在获取二维码的

/**
     * 获取体验小程序的体验二维码
     * @access public
     *
     */
    public function getCssQcode()
    {
        $result = '';
        $wxAuthorizerModel = new \app\diuber\model\WxAuthorizer();
        $imageRecordModel = new \app\diuber\model\ImageRecord();
        //获取授权AccessToken
        $authorizer = $wxAuthorizerModel->getAuthorizeInfo($this->companyId);
        if(!empty($authorizer) && $authorizer['code'] == 1){
            $url = 'https://api.weixin.qq.com/wxa/get_qrcode?access_token='.$authorizer['info']['authorizer_access_token'];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $code = curl_exec($ch);
            curl_close($ch);
            //这里需要注意一下接口返回的是二进制
            if($code){
                //uploadImageBinaryAction方法二进制转成文件保存在本地然后再上传的服务器
                $imageInfo = $imageRecordModel->uploadImageBinaryAction($code);
                if($imageInfo['code'] == 1){
                    $result = $imageInfo['info'];
                    $wxAuthorizerModel->update(array('css_qrcode'=>$result),array('company_id'=>$this->companyId));
                }
            }
        }
        return $result;
    }

 

代小程序业务之将第三方提交的代码包提交审核:

需要注意的是,这里提交代码包的时候需要先去获取小程序的第三方提交代码的页面配置以及授权小程序帐号的可选类目,在这之前需要在小程序中设置好小程序信息中的服务类目,不然无法获取到授权小程序账号的可选类目,

  /**
     * 将第三方提交的代码包提交审核
     * @access public
     *
     */
    public function submitAudit()
    {
        $result = '';
        $retrunCode = 0;
        $pageRow = array();
        $wxAuthorizerModel = new \app\diuber\model\WxAuthorizer();
        $wxAuditModel = new \app\diuber\model\WxAudit();
        //获取小程序的第三方提交代码的页面配置
        $pageInfo = $wxAuditModel->getPageInfo($this->companyId);
        if(isset($pageInfo['errcode']) && $pageInfo['errcode'] == 0 && !empty($pageInfo['page_list'])){
            $pageRow['page_list'] = $pageInfo['page_list'];
        }
        //获取授权小程序帐号的可选类目
        $CategoryInfo = $wxAuditModel->getCategoryInfo($this->companyId);
        if(isset($CategoryInfo['errcode']) && $CategoryInfo['errcode'] == 0 && !empty($CategoryInfo['category_list'])){
            $pageRow['category_list'] = $CategoryInfo['category_list'];
        }
        
        if(!empty($pageRow)){
            $authorizer = $wxAuthorizerModel->getAuthorizeInfo($this->companyId);
            if(!empty($authorizer) && $authorizer['code'] == 1){
                $url = 'https://api.weixin.qq.com/wxa/submit_audit?access_token='.$authorizer['info']['authorizer_access_token'];
                $data = '{
                        "item_list": [
                            {
                                "address":"'.$pageRow['page_list'][0].'",
                                "tag":"'.$pageRow['category_list'][0]['first_class'].' '.$pageRow['category_list'][0]['second_class'].'",
                                "first_class": "'.$pageRow['category_list'][0]['first_class'].'",
                                "second_class": "'.$pageRow['category_list'][0]['second_class'].'",
                                "first_id":'.$pageRow['category_list'][0]['first_id'].',
                                "second_id":'.$pageRow['category_list'][0]['second_id'].',
                                "title": "首页"
                            }
                        ]
                    }';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $result = curl_exec($ch);
                curl_close($ch);
                $result = json_decode($result, true);
            }
        }
        
        if(isset($result['errcode']) && !empty($result['auditid'])&& $result['errcode'] == 0){
            $row = array(
                'auditid' => $result['auditid'],
                'status' => 2,  //审核状态,其中0为审核成功,1为审核失败,2为审核中
                'reason' => '',
                'company_id' => $this->companyId
            );
            //把审核的记录保存起来,以便后续查询审核状态
            $setResult = $wxAuditModel->setWxAudit($row);
            $retrunCode = 1;
        }
        return $retrunCode;
    }

 

 

getPageInfo()方法

/**
     * 获取小程序的第三方提交代码的页面配置
     * @access public
     *
     */
    public function getPageInfo($companyId)
    {
        $result = '';
        $wxAuthorizerModel = new \app\diuber\model\WxAuthorizer();
        
        $authorizer = $wxAuthorizerModel->getAuthorizeInfo($companyId);
        if(!empty($authorizer) && $authorizer['code'] == 1){
            $url = 'https://api.weixin.qq.com/wxa/get_page?access_token='.$authorizer['info']['authorizer_access_token'];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $code = curl_exec($ch);
            curl_close($ch);
            $result = json_decode($code, true);
        }
        return $result;
    }

 

getCategoryInfo()方法

 
    /**
     * 获取授权小程序帐号的可选类目
     * @access public
     *
     */
    public function getCategoryInfo($companyId)
    {
        $result = '';
        $wxAuthorizerModel = new \app\diuber\model\WxAuthorizer();
        
        $authorizer = $wxAuthorizerModel->getAuthorizeInfo($companyId);
        if(!empty($authorizer) && $authorizer['code'] == 1){
            $url = 'https://api.weixin.qq.com/wxa/get_category?access_token='.$authorizer['info']['authorizer_access_token'];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $code = curl_exec($ch);
            curl_close($ch);
            $result = json_decode($code, true);
        }
        return $result;
    }

setWxAudit()方法:

/**
    * 设置小程序审核记录
    * @access public
    *
    */
    public function setWxAudit($data)
    {
        $result = array();
        if(!empty($data['auditid']) && isset($data['status']) && isset($data['reason']) && !empty($data['company_id'])){
            $row = array(
                'auditid' => $data['auditid'],
                'status' => $data['status'],
                'reason' => $data['reason'],
                'company_id' => $data['company_id']
            );
            $existAudit = self::get(array('auditid'=>$data['auditid']));
            if($existAudit){
                $row['update_time'] = date('Y-m-d H:i:s');
                $result = self::update($row, array('auditid'=>$row['auditid']));
            }else{
                $row['create_time'] = date('Y-m-d H:i:s');
                $result = self::create($row);
            }
        }
        return $result;
    }

 

代小程序业务之查询某个指定版本的审核状态:

/**
     * 查询某个指定版本的审核状态
     * @access public
     *
     */
    public function getAuditStatus($auditid)
    {
        $result = '';
        $wxAuthorizerModel = new \app\diuber\model\WxAuthorizer();
        //获取指定审核记录
        $wxAuditRows = self::get(array('auditid'=>$auditid));
        
        if($auditid && $wxAuditRows){
            $wxAuditRows = $wxAuditRows->toArray();
            //获取授权AccessToken
            $authorizer = $wxAuthorizerModel->getAuthorizeInfo($wxAuditRows['company_id']);
            if(!empty($authorizer) && $authorizer['code'] == 1){
                $url = 'https://api.weixin.qq.com/wxa/get_auditstatus?access_token='.$authorizer['info']['authorizer_access_token'];
                $data = json_encode(array(
                    'auditid' => $auditid
                ));
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $result = curl_exec($ch);
                curl_close($ch);
                
                $result = json_decode($result, true);
                //更新审核记录状态
                if(isset($result['errcode']) && $result['errcode'] == 0){
                    $row = array(
                        'status' => $result['status'],
                        'update_time' => date('Y-m-d H:i:s')
                    );
                    if(!empty($result['reason'])){
                        $row['reason'] = $result['reason'];
                    }
                    self::update($row, array('auditid'=>$auditid));
                }
            }
        }
        return $result;
    }

 

 

代小程序业务之发布已通过审核的小程序:

  /**
     * 发布已通过审核的小程序
     * @access public
     *
     */
    public function releaseMiniApp()
    {
        $result = '';
        $retrunCode = 0;
        $wxAuthorizerModel = new \app\diuber\model\WxAuthorizer();
        //获取授权AccessToken
        $authorizer = $wxAuthorizerModel->getAuthorizeInfo($this->companyId);
        if(!empty($authorizer) && $authorizer['code'] == 1){
            $url = 'https://api.weixin.qq.com/wxa/release?access_token='.$authorizer['info']['authorizer_access_token'];
            $data = '{}';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $result = curl_exec($ch);
            curl_close($ch);
            
            $result = json_decode($result, true);
        }
        
        if(isset($result['errcode']) && $result['errcode'] == 0){
            $retrunCode = 1;
        }
        return $retrunCode;
    }

到此从新建第三方平台、全网发布、授权流程、以及代小程序开发的一些基本方法都已经有了。

微信第三方平台发开详解结束。有问题的同学可以加我QQ:983382092交流学习,注:加的时候请填上备注,不然不要怪我拒绝,谢谢!

转载于:https://my.oschina.net/u/3463279/blog/1558815

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值