微信 第三方开放平台 服务型 小程序使用demo 二_wxopenservice-程序员宅基地

技术标签: 第三方开放平台  微信  PHP  php  小程序  

上期说过的微信授权完成后!终于可以开始正经地写接口API了,躺完坑后,现在舒服多了,直接封装了十几个接口!

就是这些了

我的代码是分 控制器 逻辑层和数据层的

首先是控制器

<?php


namespace app\common\controller;


use app\common\model\WxOpenModel;

class WxOpen
{
    private $WC;

    public function __construct()
    {
        $this->WC = new WxOpenModel();
    }

    ##############授权绑定小程序#############

    /**
     * 获取令牌
     */
    public function componentAccessToken()
    {
        $this->WC->componentAccessToken();
    }

    /**
     * 获取预授权码
     */
    public function preAuthCode()
    {
        //获取令牌
        $this->WC->componentAccessToken();
        //获取预授权码
        $this->WC->preAuthCode();
    }

    /**
     * 使用授权码获取授权信息 3
     */
    public function authorizationInfo($authorization_code)
    {
        $this->WC->authorizationInfo($authorization_code);
    }

    /**
     * 创建开放平台帐号并绑定公众号/小程序 4
     */
    public function createAccount()
    {
        $this->WC->createAccount();
    }

    /**
     * 将公众号/小程序绑定到开放平台帐号下 5
     */
    public function bindingAccount()
    {
        $this->WC->bindingAccount();
    }


    ##############开发小程序#############

    /**
     * 获取代码草稿列表
     */
    public function draftList()
    {
        $this->componentAccessToken();
        $this->WC->draftList();
    }

    /**
     * 将草稿添加到代码模板库
     */
    public function addDraftList($draft_id)
    {
        $this->WC->addDraftList($draft_id);
    }

    /**
     * 获取代码模板列表
     */
    public function templateList()
    {
        $this->WC->templateList();
    }

    /**
     * 上传小程序代码
     */
    public function upCode()
    {
        $this->WC->upCode();
    }

    /**
     * 获取体验版二维码
     */
    public function getCode()
    {
        $this->WC->getCode();
    }

    /**
     * 提交审核
     */
    public function applyCode()
    {
        $this->WC->applyCode();
    }


    /**
     * 查询指定发布审核单的审核状态
     */
    public function selectApply()
    {
        $this->WC->selectApply();
    }

    /**
     * 查询最新一次提交的审核状态
     */
    public function selectNewApply()
    {
        $this->WC->selectNewApply();
    }

    /**
     * 发布已通过审核的小程序
     */
    public function release()
    {
        $this->WC->release();
    }

    /**
     * 版本回退
     */
    public function rollbackCode()
    {
        $this->WC->rollbackCode();
    }

    /**
     * 设置最低基础库版本
     */
    public function setVersion()
    {
        $this->WC->setVersion();
    }

}



逻辑层

<?php


namespace app\common\model;


use app\common\controller\Redis;
use app\common\service\WxOpenService;

class WxOpenModel
{
    public function __construct()
    {
        new WxOpenService();
    }

    /**
     * 令牌的获取是有限制的,每个令牌的有效期为 2 小时,在令牌快过期时(比如1小时50分),重新调用接口获取
     * 获取令牌 1
     * [AppId] => 
     * [CreateTime] => 1594886696
     * [InfoType] => component_verify_ticket
     * [ComponentVerifyTicket] => 
     */
    public function componentAccessToken()
    {
        //拿票据
        $R = New Redis();
        //先判断令牌有没有过期
        $component = $R->redis_str_get('component_access_token');
        if (($component['add_time'] + 6000) < time()) {
            //未过期
            WxOpenService::$component_access_token = $component['component_access_token'];
        } else {

            $encrypt = $R->redis_str_get('encrypt');
            $option  = [
                "component_appid"         => WxOpenService::$component_appid,
                "component_appsecret"     => WxOpenService::$component_appsecret,
                "component_verify_ticket" => $encrypt['ComponentVerifyTicket']
            ];

            $list                                  = WxOpenService::RequestPostCurl(WxOpenService::$componentAccessTokenUrl, $option);
            WxOpenService::$component_access_token = $list['component_access_token'];

            $list['add_time'] = time();
            $R->redis_str_set('component_access_token', $list);
        }
    }

    /**
     * 获取预授权码 2
     */
    public function preAuthCode()
    {
        $option                       = [
            "component_appid" => WxOpenService::$component_appid,
        ];
        WxOpenService::$pre_auth_code = WxOpenService::RequestPostCurl(WxOpenService::$preAuthCodeUrl . WxOpenService::$component_access_token, $option);
    }

    /**
     * 使用授权码获取授权信息 3
     */
    public function authorizationInfo($authorization_code)
    {
        WxOpenService::$authorization_code = $authorization_code;
        $option                            = [
            "component_appid"    => WxOpenService::$component_appid,
            "authorization_code" => WxOpenService::$authorization_code,
        ];
        WxOpenService::$authorization_info = WxOpenService::RequestPostCurl(WxOpenService::$authorizationInfoUrl . WxOpenService::$component_access_token, $option);

    }

    /**
     * 创建开放平台帐号并绑定公众号/小程序 4
     */
    public function createAccount()
    {
        $option = [
            "appid" => WxOpenService::$authorization_info['authorizer_appid'],
        ];
        $list   = WxOpenService::RequestPostCurl(WxOpenService::$createAccountUrl . WxOpenService::$authorization_info['authorizer_access_token'], $option);

        if ($list['errcode'] != 0) {
            WxOpenService::log('创建开放平台帐号并绑定公众号/小程序失败');
        }

        WxOpenService::$open_appid = $list['open_appid'];
        WxOpenService::log('创建开放平台帐号并绑定公众号/小程序成功');
    }

    /**
     * 将公众号/小程序绑定到开放平台帐号下 5
     */
    public function bindingAccount()
    {
        $option = [
            "appid"      => WxOpenService::$authorization_info['authorizer_appid'],
            "open_appid" => WxOpenService::$open_appid,
        ];
        $list   = WxOpenService::RequestPostCurl(WxOpenService::$bindingAccountUrl . WxOpenService::$authorization_info['authorizer_access_token'], $option);
        if ($list['errcode'] != 0) {
            WxOpenService::log('将公众号/小程序绑定到开放平台帐号下失败');
        }
        WxOpenService::log($list);
        WxOpenService::log('将公众号/小程序绑定到开放平台帐号下成功');

    }

    /**
     * 获取代码草稿列表
     */
    public function draftList()
    {
        $list = WxOpenService::RequestGetCurl(WxOpenService::$draftUrl . WxOpenService::$component_access_token);
        if ($list['errcode'] != 0) {
            WxOpenService::log('获取代码草稿列表失败');
            output_errors('获取代码草稿列表失败');
        }
        output_data($list);
    }

    /**
     * 将草稿添加到代码模板库
     */
    public function addDraftList($draft_id)
    {
        $option = [
            "draft_id" => $draft_id,
        ];
        $list   = WxOpenService::RequestPostCurl(WxOpenService::$addDraftUrl . WxOpenService::$component_access_token, $option);
        if ($list['errcode'] != 0) {
            WxOpenService::log('将草稿添加到代码模板库失败');
            output_errors('添加失败');
        }
        output_data('添加成功');
    }

    /**
     * 获取代码模板列表
     */
    public function templateList()
    {
        $list = WxOpenService::RequestGetCurl(WxOpenService::$GetTemplateUrl . WxOpenService::$component_access_token);
        if ($list['errcode'] != 0) {
            WxOpenService::log('获取代码模板列表失败');
            output_errors('获取代码模板列表失败');
        }
        output_data($list);
    }

    /**
     * 上传小程序代码
     */
    public function upCode()
    {
        WxOpenService::check(['template_id', 'ext_json', 'user_version', 'user_desc']);
        $option = [
            "template_id"  => $_POST['template_id'],
            "ext_json"     => $_POST['ext_json'],
            "user_version" => $_POST['user_version'],
            "user_desc"    => $_POST['user_desc'],
        ];
        $list   = WxOpenService::RequestPostCurl(WxOpenService::$upCodeUrl . WxOpenService::$component_access_token, $option);
        if ($list['errcode'] != 0) {
            WxOpenService::log('将上传小程序代码失败');
        }
        WxOpenService::log($list);
        WxOpenService::log('上传小程序代码成功');
        output_data('成功');

    }

    /**
     * 获取体验版二维码
     */
    public function getCode()
    {
        $path = '/pages/index/index';
        $path = urlencode($path);
        $list = WxOpenService::RequestGetCurl(WxOpenService::$getCodeUrl . WxOpenService::$component_access_token . '&path=' . $path);

        WxOpenService::log('获取体验版二维码');
        output_data($list);
    }

    /**
     * 提交审核
     */
    public function applyCode()
    {
        $option = [
        ];
        $list   = WxOpenService::RequestPostCurl(WxOpenService::$applyCodeUrl . WxOpenService::$component_access_token, $option);
        if ($list['errcode'] != 0) {
            WxOpenService::log('提交审核失败');
        }
        WxOpenService::log($list);
        WxOpenService::log('提交审核成功');
        output_data('成功');

    }

    /**
     * 查询指定发布审核单的审核状态
     */
    public function selectApply()
    {
        WxOpenService::check(['auditid']);
        $option = [
            'auditid' => $_POST['auditid']
        ];
        $list   = WxOpenService::RequestPostCurl(WxOpenService::$selectApplyUrl . WxOpenService::$component_access_token, $option);
        if ($list['errcode'] != 0) {
            WxOpenService::log('查询指定发布审核单的审核状态失败');
        }
        switch ($list['status']) {
            case 0 :
                $list['status_name'] = '审核成功';
                break;
            case 1 :
                $list['status_name'] = '审核被拒绝';
                break;
            case 2 :
                $list['status_name'] = '审核中';
                break;
            case 3 :
                $list['status_name'] = '已撤回';
                break;
            case 4 :
                $list['status_name'] = '审核延后';
                break;
        }
        WxOpenService::log($list);
        WxOpenService::log('查询指定发布审核单的审核状态成功');
        output_data($list);
    }

    /**
     * 查询最新一次提交的审核状态
     */
    public function selectNewApply()
    {
        $list = WxOpenService::RequestGetCurl(WxOpenService::$selectNewApplyUrl . WxOpenService::$component_access_token);
        if ($list['errcode'] != 0) {
            WxOpenService::log('查询最新一次提交的审核状态失败');
        }
        switch ($list['status']) {
            case 0 :
                $list['status_name'] = '审核成功';
                break;
            case 1 :
                $list['status_name'] = '审核被拒绝';
                break;
            case 2 :
                $list['status_name'] = '审核中';
                break;
            case 3 :
                $list['status_name'] = '已撤回';
                break;
        }
        WxOpenService::log($list);
        WxOpenService::log('查询最新一次提交的审核状态成功');
        output_data($list);
    }
    /**
     * 发布已通过审核的小程序
     */
    public function release()
    {
        $option = [
        ];
        $list   = WxOpenService::RequestPostCurl(WxOpenService::$releaseUrl . WxOpenService::$component_access_token, $option);
        if ($list['errcode'] != 0) {
            WxOpenService::log('发布已通过审核的小程序失败');
        }
        WxOpenService::log($list);
        WxOpenService::log('发布已通过审核的小程序成功');
        output_data($list);
    }

    /**
     * 版本回退
     */
    public function rollbackCode()
    {
        $list = WxOpenService::RequestGetCurl(WxOpenService::$rollbackCodeUrl . WxOpenService::$component_access_token);

        if ($list['errcode'] != 0) {
            WxOpenService::log('版本回退失败');
        }
        WxOpenService::log($list);
        WxOpenService::log('版本回退成功');
        output_data($list);
    }

    /**
     * 设置最低基础库版本
     */
    public function setVersion()
    {
        WxOpenService::check(['version']);
        $option = [
            'version'=>$_POST['version']
        ];
        $list   = WxOpenService::RequestPostCurl(WxOpenService::$setVersion . WxOpenService::$component_access_token, $option);
        if ($list['errcode'] != 0) {
            WxOpenService::log('设置最低基础库版本失败');
        }
        WxOpenService::log($list);
        WxOpenService::log('设置最低基础库版本成功');
        output_data($list);
    }

}

 

最后是数据层

 

<?php


namespace app\common\service;


use app\common\ApiCommon;
use app\pay\service\PayService;
use lib\Curl;

class WxOpenService extends ApiCommon
{
    //开放平台appid
    public static $component_appid='';
    //开放平台appsecret
    public static $component_appsecret='';

    //令牌
    public static $component_access_token;
    //预授权码
    public static $pre_auth_code;
    //授权码
    public static $authorization_code;
    //获取授权信息
    public static $authorization_info;
    //所创建的开放平台帐号的 appid
    public static $open_appid;
    //代码草稿列表
    public static $draft_list;
    //代码模板列表
    public static $template_list;


    //令牌
    public static $componentAccessTokenUrl='https://api.weixin.qq.com/cgi-bin/component/api_component_token';
    //预授权码
    public static $preAuthCodeUrl='https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=';
    //预授权码获取授权码
    public static $authorizationCodeUrl='https://mp.weixin.qq.com/cgi-bin/componentloginpage?';
    //预授权码获取授权码 回调 URI
    public static $redirectUrl='https://master.jiaju01.com/api/Wx/GetAuthorizationCode';
    //使用授权码获取授权信息
    public static $authorizationInfoUrl='https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=';
    //创建开放平台帐号并绑定公众号/小程序
    public static $createAccountUrl='https://api.weixin.qq.com/cgi-bin/open/create?access_token=';
    //将公众号/小程序绑定到开放平台帐号下
    public static $bindingAccountUrl='https://api.weixin.qq.com/cgi-bin/open/bind?access_token=';
    //获取代码草稿列表
    public static $draftUrl='https://api.weixin.qq.com/wxa/gettemplatedraftlist?access_token=';
    //将草稿添加到代码模板库
    public static $addDraftUrl='https://api.weixin.qq.com/wxa/gettemplatedraftlist?access_token=';
    //获取代码模板列表
    public static $GetTemplateUrl='https://api.weixin.qq.com/wxa/gettemplatelist?access_token=';
    //上传小程序代码
    public static $upCodeUrl='https://api.weixin.qq.com/wxa/commit?access_token=';
    //获取体验版二维码
    public static $getCodeUrl='https://api.weixin.qq.com/wxa/get_qrcode?access_token=';
    //提交审核
    public static $applyCodeUrl='https://api.weixin.qq.com/wxa/submit_audit?access_token=';
    //查询指定发布审核单的审核状态
    public static $selectApplyUrl='https://api.weixin.qq.com/wxa/get_auditstatus?access_token=';
    //查询最新一次提交的审核状态
    public static $selectNewApplyUrl='https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=';
    //发布已通过审核的小程序
    public static $releaseUrl='https://api.weixin.qq.com/wxa/release?access_token=';
    //版本回退
    public static $rollbackCodeUrl='https://api.weixin.qq.com/wxa/revertcoderelease?access_token=';
    //设置最低基础库版本
    public static $setVersion='https://api.weixin.qq.com/cgi-bin/wxopen/setweappsupportversion?access_token=';




    public function __construct()
    {
        //初始化父类
        parent::__construct();
    }

    /**
     * URL请求(GET)
     */
    public static function RequestGetCurl($url)
    {
        $curl = new  Curl();
        $curl->setUrl($url);
        $list = $curl->execute(true);
        $curl->close();
        return $list;
    }

    /**
     * URL请求(POST)
     */
    public static function RequestPostCurl($url, $xmlData)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url); //定义表单提交地址
        curl_setopt($curl, CURLOPT_POST, 1);   //定义提交类型 1:POST ;0:GET 设置post方式提交
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, 'Content-type: text/xml');
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HEADER, 0);            //定义是否显示状态头 1:显示 ; 0:不显示
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //定义是否直接输出返回流
        curl_setopt($curl, CURLOPT_POSTFIELDS, $xmlData); //定义提交的数据,这里是XML文件

        $returnData = curl_exec($curl);
        return $returnData;
    }

    public static function log($msg){
        if(WxOpenService::$authorization_info['authorizer_appid']){
            WxOpenService::p('小程序:' . WxOpenService::$authorization_info['authorizer_appid'], false, 'wx');
        }

        WxOpenService::p($msg, false, 'wx');
        WxOpenService::p(date('Y-m-d H:i:s',time()), false, 'wx');
    }

}

这块还是比较简单的,直接封装自己想用的就行了!!!
加油各位,胜利就在前方!
有坑可以留言哦
 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq284944970/article/details/107425111

智能推荐

BT1120中的串行传输-程序员宅基地

文章浏览阅读566次。BT1120不仅支持并行传输,也定义了并行传输。详细说明可以看ITU-R BT1120,在这里只做概述和总结。转载于:https://www.cnblogs.com/zhongguo135/p/8405665.html_bt1120传输速率

Parameter tasks is deprecated, use target instead-程序员宅基地

文章浏览阅读4.1k次。原因:<tasks></tasks><plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version&g..._parameter tasks is deprecated, use target instead

用xshell连接l自己的inux-程序员宅基地

文章浏览阅读55次。有时候连接会提示失败(当然确保账号密码没错),这里需要安装一个服务,ssh服务器1)ubuntu安装ssh服务器sudo apt-get install openssh-server2)出现问题时,重启ssh服务即可sudo service ssh restart转载于:https://www.cnblogs.com/wzqstudy/p/10532694.html..._xshelll http

解决 Zuul 中 OAuth2 报 unauthorized 错误-程序员宅基地

文章浏览阅读2.8k次。问题描述微服务中使用 OAuth2 鉴权,直接访问正常,通过 Zuul 访问报错:{ "error": "unauthorized", "error_description": "Full authentication is required to access this resource"}解决方法在 Zuul 中添加配置:zuul..._error:unauthorized

大道五目Flash英文版(Renju Problems)程序分析之禁手判断-程序员宅基地

文章浏览阅读110次。现在界面已经完成了,刚刚完成了禁手算法,把代码共享出来:CodeprivatefunctionIsForbidden(x:int,y:int,board:Array):int{varindex:int=x*15+y;//setthisposition(x,y)toblac..._程序判断禁手

(转)淘淘商城系列——商品搜索功能测试-程序员宅基地

文章浏览阅读107次。http://blog.csdn.net/yerenyuan_pku/article/details/72941506到这里,我相信大家也是不容易,我自己也算是很不容易写到这里,希望自己能一直写下去。之前我们就差不多把商品搜索功能实现了,本文我们来一起测试下该搜索功能。 首先我们要保证zookeeper、redis、image、solr服务都开启。接着我们把taotao-common工..._商品搜索浏览功能测试

随便推点

plus.push.getClientInfo获取客户端标识clientid_plus.push.getclientinfo()-程序员宅基地

文章浏览阅读5.2k次。方案一:let pinf = plus.push.getClientInfo();let cid = pinf && pinf.clientid || ''; //客户端标识有可能取不到clientId,或者为‘undefined’ ‘null' 等字符串由于可能取不到,然后使用方案二,异步获取方案二:plus.push.getClientInfoAsync((info) => { cid = info.clientid; }, err =&g_plus.push.getclientinfo()

Verilog仿真事件队列-程序员宅基地

文章浏览阅读876次。1.分层的事件队列2.执行事件的队列3.仿真时间的计算4.同一层事件,无先后顺序这个点:觉得Verilog与systemVerilog比较,Verilog比较笼统,systemVerilog则比较细分。在Verilog眼中无论testbench、dut还是assertion都是code。所以先把code吃进来,然后有一个时间轴参数,仅仅处理set t = 0时刻的code...._verilog 事件队列

conda中设置源_conda 源-程序员宅基地

文章浏览阅读1w次,点赞3次,收藏12次。文章目录添加源清华源腾讯源移除源清华源腾讯源打印当前channels系统中的配置文件使用pip源添加源清华源conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/conda config --add channels h_conda 源

Linux下USB转串口的驱动【转】-程序员宅基地

文章浏览阅读42次。转自:http://www.linuxidc.com/Linux/2011-02/32218.htmLinux发行版自带usb to serial驱动,以模块方式编译驱动,在内核源代码目录下运行Make MenuConfig选择Devces drivers-->USB seupport--> <M>USB Serial Converter support --> ..._ttyusb 需要哪些ko

Python字符串格式化方法及对比分析:百分号与format方式-程序员宅基地

文章浏览阅读259次。字符串格式化目前有两种方式:一、“%”方式;二、format方式;一、“%”方式1、%传值:%s:可以接收任何值;%d:接收数字;1 msg = 'my name is %s' %'zhangsan' #str类型2 msg1 = 'he is %s' %20 #he is 20 int类型3 msg2 = 'she likes %s' %['apple','orange','pai'] #..._pylance 只有提示 无法自动格式化

深入理解Thread.sleep()函数_thread sleep-程序员宅基地

文章浏览阅读1.4k次,点赞5次,收藏5次。目录前言回顾操作系统原理时间片算法抢占式操作系统前言我们可能经常会用到 Thread.sleep() 函数来使线程挂起一段时间。那么你有没有正确的理解这个函数的用法呢?思考下面这两个问题假设现在是 2008-4-7 12:00:00.000,如果我调用一下 Thread.sleep(1000) ,在 2008-4-7 12:00:01.000 的时候,这个线程会不会被唤醒?某人的代码中用了一句看似莫明其妙的话:Thread.sleep(0) 。既然是 sleep 0 毫秒,那么他跟去掉这句代码相_thread sleep

推荐文章

热门文章

相关标签