微信第三方平臺開發詳解——PHP版

微信第三方平臺開發詳解之申請以及全網發佈流程 css

微信第三方平臺開發詳解之受權流程 html

微信第三方平臺開發詳解之代小程序開發json

 

補上上一章的刷新受權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;
    }api

 

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功能就完善了。app

 

代小程序業務之修改服務器地址dom

這裏博主被坑了好久第三方小程序上傳好代碼後,真機上只有打開vconsole的時候才能調通接口,關閉vsonsole就不能調接口了,後來才發現須要把第三方小程序的服務器地址改成本身的服務器地址,否則第三方小程序不能調用本身服務器上的接口。curl

 

/**
     * 修改服務器地址
     * @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交流學習,注:加的時候請填上備註,否則不要怪我拒絕,謝謝!

相關文章
相關標籤/搜索