WEB开发者-分享WEB开发知识,让开发变得更简单!

小程序授权第三方平台

参考链接:http://www.webkfz.com/weixin-kaifa-406993.html
首先在微信开放平台创建第三方平台,审核通过后
然后可以测试将指定的微信公众号或小程序授权第三方平台
授权流程参考官方文档:
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1453779503&token=9affd10a1f49bd2c84634fc3c798debd00eeeae3&lang=zh_CN

public function xiaochengxu_event()
{
    trace('小程序推送消息', 'smallroutine');
    $token = XXX; //第三方平台token
    $encodingAesKey = XXX; //第三方平台encoding_aes_key
    $component_appid = XXX; //第三方平台appid
    if ($token && $encodingAesKey && $component_appid) {
        trace("执行中...", 'smallroutine');
        $timeStamp = $this->request->param('timestamp');
        $nonce = $this->request->param('nonce');
        $msg_sign = $this->request->param('msg_signature');
        trace(['timeStamp' => $timeStamp, 'nonce' => $nonce, 'msg_sign' => $msg_sign], 'smallroutine');
        $encryptMsg = file_get_contents('php://input');
        trace(['encryptMsg' => $encryptMsg], 'smallroutine');
        try {
            $pc = new WXBizMsgCrypt($token, $encodingAesKey, $component_appid);
            $xml_tree = new \DOMDocument();
            $xml_tree->loadXML($encryptMsg);
            $array_e = $xml_tree->getElementsByTagName('Encrypt');
            $encrypt = $array_e->item(0)->nodeValue;
            trace(['encrypt' => $encrypt], 'smallroutine');
            $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
            $from_xml = sprintf($format, $encrypt);
            trace(['from_xml' => $from_xml], 'smallroutine');
            $msg = '';
            $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
            trace(['errCode' => $errCode], 'smallroutine');
        } catch (\Exception $e) {
            trace("小程序异常信息error:" . $e->getMessage(), 'smallroutine');
        }
        if ($errCode == 0) {
            $xml = new \DOMDocument();
            $xml->loadXML($msg);
            $array_type = $xml->getElementsByTagName('InfoType');
            $InfoType = $array_type->item(0)->nodeValue;
            switch ($InfoType) {
                case 'component_verify_ticket': //请求ticket
                    $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
                    $component_verify_ticket = $array_e->item(0)->nodeValue;
                    //缓存ticket
                    $ticketKey = $component_appid . "_componentVerifyTicket";
                    Cache::store('redis')->rm($ticketKey);
                    Cache::store('redis')->tag('component_verify_ticket')->set($ticketKey, $component_verify_ticket, 1800);
                    $this->updateAccessToken($component_verify_ticket, $component_appid);
                    echo "success";
                    trace('获取成功', 'smallroutine');
                    break;
            }
        } else {
            echo "false";
            trace('接收微信官方推送的消息失败:' . $errCode, 'smallroutine');
        }
    } else {
        trace('未配置参数', 'smallroutine');
    }           
}   
//更新component_access_token  存redis
public function updateAccessToken($component_verify_ticket, $component_appid)
{
    trace(['获取第三方平台component_access_token'], "smallroutine");
    trace("component_appid:$component_appid", "smallroutine");
    $small_appsecret = config('site.small_three_appsecret');
    $accessTokenKey = $component_appid . "_component_access_token";
    $component_access_token = Cache::store('redis')->get($accessTokenKey);
    if (!$component_access_token) {
        $apiUrl = 'https://www.webkfz.com/d/file/20200911081359/2020091108111360
        $data = '{"component_appid":"' . $component_appid . '" ,"component_appsecret": "' . $small_appsecret . '","component_verify_ticket": "' . $component_verify_ticket . '"}';
        $json = json_decode(Http::post($apiUrl, $data));
        if (isset($json->component_access_token)) {
            $component_access_token = $json->component_access_token;
            Cache::store('redis')->tag('component_access_token')->set($accessTokenKey, $component_access_token, 3600);
        }
        trace("json:" . json_encode($json), "smallroutine");
        trace("component_access_token:" . $json->component_access_token, "smallroutine");
    }
    return $component_access_token;
}
//授权流程:
<?php
namespace app\admin\controller\wechatprogram;
use app\common\controller\Backend;
use app\common\components\wechatprogram\StartAuth;
use app\common\components\wechatprogram\MiniProgram;
use think\Db;

/**
 * 微信小程序提交审核的小程序
 *
 * @icon fa fa-circle-o
 */
class Audit extends Backend
{
/**
 * WxminiprogramAudit模型对象
 * @var \app\admin\model\WxminiprogramAudit
 */
protected $model = null;
protected $authorizer_appid;
protected $limitAppId;
protected $set_server_domain;

public function _initialize()
{
    parent::_initialize();
    $this->model = model('WxminiprogramAudit');
    $wxminiprograms = Db::name("wxminiprograms")->where("app_id", $GLOBALS['app_id'])->field('authorizer_appid,set_server_domain')->find();
    $this->authorizer_appid = $wxminiprograms['authorizer_appid'];
    $this->set_server_domain = $wxminiprograms['set_server_domain'];
    $this->view->assign("statusList", $this->model->getStatusList());
    $this->view->assign("set_server_domain",$wxminiprograms['set_server_domain']);
}

/**
 * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
 * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
 * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
 */

/**
 * 小程序授权提交审核页面
 */
public function wxaudit()
{
    return $this->view->fetch();
}
/**
 * 小程序部署流程
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 */
public function doAction()
{
    if ($this->request->isPost()) {
        $app_id = $GLOBALS['app_id'];
        $action = $this->request->param('type');
        if ($action == 'auth') {
            if ($this->authorizer_appid) {
                $this->error("小程序已授权");
            }
            //授权回调URI
            $request = request();
            $current_domain = $request->server('HTTP_HOST');  //当前服务器域名
            $domain = "http://api.dhcc.wang";
            $redirect_uri = $domain . "/api/notify/smallCallback/app_id/{$app_id}/domain/{$current_domain}";
            $auth = new StartAuth();
            $url = $auth->startAuth($redirect_uri, $auth_type = 3, $app_id);
            if ($url) {
                //扫码授权URL
                $url = urlencode($url);
                $auth_url = $domain . "/index/Smallnotify/smallProgramAuth" . "?auth_url=" . $url;
                $this->success("点击授权扫码地址授权", $auth_url, $url);
            }
        }
        $this->authorizer();
        $this->release_version($app_id);
        $mini = new Miniprogram();
        if ($action == 'setServerDomain') {
            if($this->set_server_domain){
                $this->error("服务器域名已设置");
            }
            $domain_api = config('site.small_three_serverdomain');
            if (!$domain_api) {
                $this->error("请先设置服务器域名");
            }
            if ($mini->setServerDomain($domain_api, $app_id)) {
                $this->success("设置小程序服务器域名操作成功");
            } else {
                $this->error("设置小程序服务器域名操作失败或已设置");
            }
        } elseif ($action == 'uploadCode') {
            $template_id = $this->request->param('template_id');
            if (!$template_id) {
                $this->error('请输入代码库中的代码模版ID');
            }
            $templateInfo = Db::name("weixin_template")->where('template_id', $template_id)->find();
            if (!$templateInfo) {
                $this->error('模板信息不存在');
            }
            //上传小程序代码
            if ($mini->uploadCode($template_id, $templateInfo['user_version'], $templateInfo['user_desc'])) {
                $this->success('上传小程序代码操作成功');
            } else {
                $this->error('上传小程序代码操作失败,请查看日志');
            }
        } elseif ($action == 'getExpVersion') {
            //获取体验小程序的体验二维码
            $qrcode = $mini->getExpVersion();
            if ($qrcode) {
                $this->success("获取成功", $qrcode);
            } else {
                $this->error('获取体验小程序的体验二维码操作失败');
            }
        } elseif ($action == 'review') {
            //提交审核
            $auditid = Db::name('wxminiprogram_audit')
                ->where(['app_id' => $GLOBALS['app_id'], 'status' => ['not in', [0, 1]]])
                ->order('create_time', 'desc')
                ->value('auditid');
            if ($auditid) {
                $this->error("有待处理的版本,请先处理该版本相关事项再提交新的审核。审核ID:'.$auditid.'");
            } else {
                if ($mini->submitReview()) {
                    $this->success("小程序提交审核操作成功");
                } else {
                    $this->error("小程序提交审核操作失败,请查看日志");
                }
            }
        } elseif ($action == 'getAudit') {
            //查询指定版本的审核状态
            $auditid = $this->request->param('auditid');
            if ($auditid) {
                if ($mini->getAuditStatus($auditid)) {
                    $audit = Db::name('wxminiprogram_audit')
                        ->where(['app_id' => $GLOBALS['app_id'], 'authorizer_appid' => $this->authorizer_appid, 'auditid' => $auditid])
                        ->field('status,reason')
                        ->find();
                    if ($audit['status'] == 0) {
                        $this->success('该版本审核已通过');
                    } elseif ($audit['status'] == 1) {
                        $this->error("该版本审核失败,原因:" . $audit['reason']);
                    } elseif ($audit['status'] == 2) {
                        $this->error("该版本小程序正在审核中......");
                    } else {
                        $this->error("未知状态......");
                    }
                } else {
                    $this->error("查询指定版本的审核状态操作失败,请查看日志");
                }
            } else {
                $this->error("请输入要查询的审核ID");
            }
        } elseif ($action == 'lastAudit') {
            //查询最新一次提交的审核状态
            $auditid = $mini->getLastAudit();
            if ($auditid) {
                $audit = Db::name('wxminiprogram_audit')
                    ->where(['app_id' => $GLOBALS['app_id'], 'authorizer_appid' => $this->authorizer_appid, 'auditid' => $auditid])
                    ->field('status,reason')
                    ->find();
                if ($audit['status'] == 0) {
                    $this->success("审核已通过");
                } elseif ($audit['status'] == 1) {
                    $this->error("审核失败,原因:" . $audit['reason']);
                } elseif ($audit['status'] == 2) {
                    $this->error("小程序正在审核中......");
                } else {
                    $this->error("未知状态......");
                }
            } else {
                $this->error("查询最新一次提交的审核状态操作失败");
            }
        } elseif ($action == 'release') {
            //发布已通过审核的小程序
            $auditid = Db::name('wxminiprogram_audit')
                ->where(['app_id' => $GLOBALS['app_id'], 'authorizer_appid' => $this->authorizer_appid, 'status' => ['neq', 0]])
                ->order('create_time', 'desc')
                ->value('auditid');
            if ($auditid) {
                $this->error("有待处理的版本,请先处理该版本相关事项再发布版本。审核ID:" . $auditid);
            } else {
                $errcode = $mini->release();
                if ($errcode) {
                    $this->success("已发版");
                } else {
                    $this->error("发布失败,错误代码:" . $errcode);
                }
            }
        }
    }
}

/**
 * 是否授权
 */
public function authorizer()
{
    if (!$this->authorizer_appid) {
        $this->error("请先完成授权后操作!");
    }
}

/**
 * 发布版本限制
 * @param $app_id
 * @throws \think\Exception
 */
public function release_version($app_id)
{
    $today = strtotime(date('Y-m-d'));
    $num = Db::name("wxminiprogram_audit")->where("app_id", $app_id)->where("create_time", '>', $today)->count();
    if ($num > 5) {
        $this->error("每天最多发布5个版本,今日已达上限!");
    }
}
    }
<?php

namespace app\common\components\wechatprogram;

use fast\Random;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;
use fast\Http;

/**
 * 微信第三方平台授权流程
 * Class StartAuth
 * @package app\common\components\wechatprogram
 */
class StartAuth
{
    public $appid;              //第三方平台应用appid
    public $appsecret;          //第三方平台应用appsecret
    public $token;              //第三方平台应用token(消息校验Token)
    public $encodingAesKey;     //第三方平台应用Key(消息加解密Key)
    public $component_ticket;   //微信后台推送的ticket,用于获取第三方平台接口调用凭据
    public $component_access_token;   //获取自己的接口调用凭据(component_access_token)
    const API_URL = '请求服务器链接/';

    public function __construct()
    {
        $small_three_appid = config('site.small_three_appid');
        $this->appid = $small_three_appid;
        $this->appsecret = config('site.small_three_appsecret');
        $this->token = config('site.small_three_appsecret');
        $this->encodingAesKey = config('site.small_encoding_aes_key');
//        $this->component_ticket = Db::name("weixin_account")->where('component_appid', $small_three_appid)->value('component_verify_ticket');

        $componentUrl = self::API_URL . "api/small_program/getComponentInfo";
        $componentInfo = json_decode(Http::get($componentUrl), true);
        $this->component_ticket = $componentInfo['data']['component_verify_ticket'];
        $this->component_access_token = $componentInfo['data']['component_access_token'];
    }

    /**
     * 扫码授权,注意此URL必须放置在页面当中用户点击进行跳转,不能通过程序跳转,否则将出现“请确认授权入口页所在域名,与授权后回调页所在域名相同....”错误
     * @param $redirect_uri string 扫码成功后的回调地址
     * @param int $auth_type 授权类型,1公众号,2小程序,3公众号/小程序同时展现。不传参数默认都展示
     * @param $app_id
     * @return string
     * @throws Exception
     * @throws \think\exception\PDOException
     */

    public function startAuth($redirect_uri, $auth_type = 3, $app_id)
    {
        $url = "https://www.webkfz.com/d/file/20200911081361/2020091108111362" . $this->appid . "&pre_auth_code=" . $this->get_pre_auth_code($app_id) . "&redirect_uri=" . urlencode($redirect_uri) . "&auth_type=" . $auth_type;
        return $url;
    }

    /**
     * 获取第三方平台component_access_token
     * 此值应保存
     * @return mixed
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function get_component_access_token()
    {

//        $url = "https://www.webkfz.com/d/file/20200911081363/2020091108111364
//        $data = '{
//            "component_appid":"' . $this->appid . '" ,
//            "component_appsecret": "' . $this->appsecret . '",
//            "component_verify_ticket": "' . $this->component_ticket . '"
//        }';
//        $component = Db::name("weixin_account")->where('component_appid', $this->appid)->field("token_expires,component_access_token")->find();
//        if ($component['token_expires'] <= time()) {
//            $ret = json_decode($this->https_post($url, $data), true);
//            if (isset($ret['component_access_token'])) {
//                //实际有效期2小时7200
//                $token_expires = time() + 3600;
//                $save = ["token_expires" => $token_expires, "component_access_token" => $ret['component_access_token']];
//                Db::name("weixin_account")->where('component_appid', $this->appid)->update($save);
//                return $ret['component_access_token'];
//            } else {
//                trace(['获取第三方平台component_access_token失败'], "smallroutine_callback");
//                trace(['ret' => $ret], "smallroutine_callback");
//                throw new Exception("获取第三方平台component_access_token失败:".json_encode($ret));
//            }
//        } else {
//            return $component['component_access_token'];
//        }

        $component_access_token = $this->component_access_token;
        if (!$component_access_token) {
            $url = "https://www.webkfz.com/d/file/20200911081363/2020091108111364
            $data = '{
                "component_appid":"' . $this->appid . '" ,
                "component_appsecret": "' . $this->appsecret . '",
                "component_verify_ticket": "' . $this->component_ticket . '"
            }';
            $ret = json_decode($this->https_post($url, $data), true);
            if (isset($ret['component_access_token'])) {
                return $ret['component_access_token'];
            } else {
                trace(['获取第三方平台component_access_token失败'], "smallroutine_callback");
                throw new Exception("获取第三方平台component_access_token失败:" . json_encode($ret));
            }
        }
        return $component_access_token;
    }

    /**
     * 第三方平台方获取预授权码pre_auth_code
     * @param $app_id
     * @return mixed
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    private function get_pre_auth_code($app_id)
    {
        $url = "https://www.webkfz.com/d/file/20200911081365/2020091108111366" . $this->get_component_access_token($app_id);
        $data = '{"component_appid":"' . $this->appid . '"}';
        $preAuthInfo = Db::name("app")->field('pre_auth_code,pre_auth_expires')->where("id", $app_id)->find();
        if ($preAuthInfo['pre_auth_expires'] <= time()) {
            $ret = json_decode($this->https_post($url, $data), true);
            if ($ret['pre_auth_code']) {
                //实际有效期10分钟
                $time = time() + 550;
                $save = ["pre_auth_code" => $ret['pre_auth_code'], "pre_auth_expires" => $time];
                Db::name("app")->where("id", $app_id)->update($save);
                return $ret['pre_auth_code'];
            } else {
                trace(['第三方平台方获取预授权码pre_auth_code失败'], "smallroutine_callback");
                trace(['ret' => $ret], "smallroutine_callback");
                throw new Exception("第三方平台方获取预授权码pre_auth_code失败:" . json_encode($ret));
            }
        } else {
            return $preAuthInfo['pre_auth_code'];
        }
    }
    /**
     * 发起POST网络提交
     * @params string $url : 网络地址
     * @params json $data : 发送的json格式数据
     * @return mixed
     */
    private function https_post($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    /**
     * 发起GET网络提交
     * @params string $url : 网络地址
     * @param $url
     * @return mixed|string
     */
    private function https_get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 60);
        if (curl_errno($curl)) {
            return 'Errno' . curl_error($curl);
        } else {
            $result = curl_exec($curl);
        }
        curl_close($curl);
        return $result;
    }
    }

    <?php
namespace app\common\components\wechatprogram;
use think\Db;
use fast\Http;
use think\Exception;

/**
 * 代小程序实现业务
 * Class StartAuth
 * @package app\common\components\wechatprogram
 */
class MiniProgram
{
    private $thirdAppId;        //开放平台appid
    private $encodingAesKey;    //开放平台encodingAesKey
    private $thirdToken;        //开放平台token
    private $thirdAccessToken;  //开放平台access_token
    private $authorizer_appid;
    private $authorizer_access_token;
    private $authorizer_refresh_token;
    private $pre_auth_code;
    private $sign_key;  //请求接口签名
    const API_URL = '请求服务器地址/';

    public function __construct()
    {
        $config = config("app_{$GLOBALS['app_id']}");
        if ($config) {
            $small_three_appid = config('site.small_three_appid');
            $this->thirdAppId = $small_three_appid;
            $this->encodingAesKey = config('site.small_encoding_aes_key');
            $this->thirdToken = config('site.small_encoding_aes_token');
//            $this->thirdAccessToken = Db::name("weixin_account")->where('component_appid',$small_three_appid)->value('component_access_token');
            $componentUrl = self::API_URL . "api/small_program/getComponentInfo";
            $componentInfo = json_decode(Http::get($componentUrl), true);
            $this->thirdAccessToken = $componentInfo['data']['component_access_token'];

            $this->pre_auth_code = $config['pre_auth_code'];

            $this->sign_key = $config['sign_key'];

            $miniprogram = Db::name('wxminiprograms')
                ->where("app_id", $GLOBALS['app_id'])
                ->field('authorizer_access_token,authorizer_refresh_token,authorizer_expires,authorizer_appid')
                ->find();
            if ($miniprogram['authorizer_appid']) {
                $this->authorizer_appid = $miniprogram['authorizer_appid'];
                if (time() > $miniprogram['authorizer_expires']) {
                    //更新授权信息
                    $miniapp = $this->update_authorizer_access_token($miniprogram['authorizer_appid'], $miniprogram['authorizer_refresh_token'], $GLOBALS['app_id']);
                    if ($miniapp) {
                        $this->authorizer_access_token = $miniapp->authorizer_access_token;
                        $this->authorizer_refresh_token = $miniapp->authorizer_refresh_token;
                    } else {
                        trace("更新小程序access_token失败authorizer_appid:{$miniprogram['authorizer_appid']}", 'smallroutine_debug');
                        exit;
                    }
                } else {
                    $this->authorizer_access_token = $miniprogram['authorizer_access_token'];
                    $this->authorizer_refresh_token = $miniprogram['authorizer_refresh_token'];
                }
            } else {
                trace("小程序不存在authorizer_appid:{$miniprogram['authorizer_appid']}", 'smallroutine_debug');
                throw new Exception("小程序不存在authorizer_appid:{$miniprogram['authorizer_appid']}");
            }
        } else {
            trace("请增加第三方平台账户信息", 'smallroutine_debug');
            throw new Exception("请增加第三方平台账户信息");
        }
    }

    /**
     * 设置小程序服务器地址,无需加https前缀,但域名必须可以通过https访问
     * @param string $domain 域名地址。只接收一维数组。
     * @param $app_id
     * @return bool
     * @throws Exception
     */
    public function setServerDomain($domain = 'test.moh.cc', $app_id)
    {
        $url = "https://www.webkfz.com/d/file/20200911081367/2020091108111368" . $this->authorizer_access_token;
        if (is_array($domain)) {
            $https = '';
            $wss = '';
            foreach ($domain as $key => $value) {
                $https .= '"https://' . $value . '",';
                $wss .= '"wss://' . $value . '",';
            }
            $https = rtrim($https, ',');
            $wss = rtrim($wss, ',');
            $data = '{
                "action":"add",
                "requestdomain":[' . $https . '],
                "wsrequestdomain":[' . $wss . '],
                "uploaddomain":[' . $https . '],
                "downloaddomain":[' . $https . ']
            }';
        } else {
            $data = '{
                "action":"add",
                "requestdomain":"https://' . $domain . '",
                "wsrequestdomain":"wss://' . $domain . '",
                "uploaddomain":"https://' . $domain . '",
                "downloaddomain":"https://' . $domain . '"
            }';
        }
        $ret = json_decode($this->https_post($url, $data));
        if ($ret->errcode == 0) {
            Db::name("wxminiprograms")->where("app_id", $app_id)->update(['set_server_domain' => 1]);
            return true;
        } else {
            trace(['设置小程序服务器地址失败'], 'smallroutine_debug');
            trace("授权appid:" . $this->authorizer_appid, 'smallroutine_debug');
            trace("授权信息:" . json_encode($ret), 'smallroutine_debug');
            throw new Exception("设置小程序服务器地址失败:" . json_encode($ret));
        }
    }

    /**
     * 设置小程序业务域名,无需加https前缀,但域名必须可以通过https访问
     * @param string $domain 域名地址。只接收一维数组。
     * @return bool
     */
    public function setBusinessDomain($domain = 'test.moh.cc')
    {
        $url = "https://www.webkfz.com/d/file/20200911081369/2020091108111370" . $this->authorizer_access_token;
        if (is_array($domain)) {
            $https = '';
            foreach ($domain as $key => $value) {
                $https .= '"https://' . $value . '",';
            }
            $https = rtrim($https, ',');
            $data = '{
                "action":"add",
                "webviewdomain":[' . $https . ']
            }';
        } else {
            $data = '{
                "action":"add",
                "webviewdomain":"https://' . $domain . '"
            }';
        }

        $ret = json_decode($this->https_post($url, $data));
        if ($ret->errcode == 0) {
            return true;
        } else {
            $this->errorLog("设置小程序业务域名失败,appid:" . $this->authorizer_appid, $ret);
            return false;
        }
    }

    /**
     * 成员管理,绑定小程序体验者
     * @param $wechatid 体验者的微信号
     * @return bool
     */
    public function bindMember($wechatid)
    {
        $url = "https://www.webkfz.com/d/file/20200911081371/2020091108111372" . $this->authorizer_access_token;
        $data = '{"wechatid":"' . $wechatid . '"}';
        $ret = json_decode($this->https_post($url, $data));
        if ($ret->errcode == 0) {
            return true;
        } else {
            $this->errorLog("绑定小程序体验者操作失败,appid:" . $this->authorizer_appid, $ret);
            return false;
        }
    }

    /**
     * 成员管理,解绑定小程序体验者
     * @param $wechatid 体验者的微信号
     * @return bool
     */
    public function unBindMember($wechatid)
    {
        $url = "https://www.webkfz.com/d/file/20200911081373/2020091108111374" . $this->authorizer_access_token;
        $data = '{"wechatid":"' . $wechatid . '"}';
        $ret = json_decode($this->https_post($url, $data));
        if ($ret->errcode == 0) {
            return true;
        } else {
            $this->errorLog("解绑定小程序体验者操作失败,appid:" . $this->authorizer_appid, $ret);
            return false;
        }
    }

    /**
     * 成员管理,获取小程序体验者列表
     * @return bool
     */
    public function listMember()
    {
        $url = "https://www.webkfz.com/d/file/20200911081375/2020091108111376" . $this->authorizer_access_token;
        $data = '{"action":"get_experiencer"}';
        $ret = json_decode($this->https_post($url, $data));
        if ($ret->errcode == 0) {
            return $ret->members;
        } else {
            $this->errorLog("获取小程序体验者列表操作失败,appid:" . $this->authorizer_appid, $ret);
            return false;
        }
    }

    /**
     * 为授权的小程序帐号上传小程序代码
     * @param int $template_id
     * @param string $user_version
     * @param string $user_desc
     * @return bool
     * @throws Exception
     */
    public function uploadCode($template_id = 1, $user_version = 'v1.0.0', $user_desc = "测试")
    {
        $domain = config('site.api_url');
        $sign_key = "xcx5" . $this->sign_key;
        $ext_json = json_encode('{"extEnable": true,"extAppid": "' . $this->thirdAppId . '","ext":{"appid": "' . $this->authorizer_appid . '","apiurl":"' . $domain . '","signkey":"' . $sign_key . '"}}');
        $url = "https://www.webkfz.com/d/file/20200911081377/2020091108111378" . $this->authorizer_access_token;
        $data = '{"template_id":"' . $template_id . '","ext_json":' . $ext_json . ',"user_version":"' . $user_version . '","user_desc":"' . $user_desc . '"}';
        $ret = json_decode($this->https_post($url, $data));
        if ($ret->errcode == 0) {
            return true;
        } else {
            trace(['为授权的小程序帐号上传小程序代码操作失败'], 'smallroutine_debug');
            trace("授权appid:" . $this->authorizer_appid, 'smallroutine_debug');
            trace("授权信息:" . json_encode($ret), 'smallroutine_debug');
            throw new Exception("为授权的小程序帐号上传小程序代码操作失败:" . json_encode($ret));
        }
    }

    /**
     * 获取体验小程序的体验二维码 指定体验版二维码跳转到某个具体页面
     * @param string $path
     * @return bool|string
     * @throws Exception
     */
    public function getExpVersion($path = '')
    {
        if ($path) {
            $url = "https://www.webkfz.com/d/file/20200911081379/2020091108111380" . $this->authorizer_access_token . "&path=" . urlencode($path);
        } else {
            $url = "https://www.webkfz.com/d/file/20200911081379/2020091108111380" . $this->authorizer_access_token;
        }
        $ret = json_decode($this->https_get($url));
        if ($ret->errcode) {
            trace(['获取体验小程序的体验二维码操作失败'], "smallroutine_debug");
            trace("授权appid:" . $this->authorizer_appid, 'smallroutine_debug');
            trace("授权信息:" . json_encode($ret), 'smallroutine_debug');
            throw new Exception("获取体验小程序的体验二维码操作失败:" . json_encode($ret));
        } else {
            return $url;
        }
    }
    /**
     * 提交审核
     * @param string $tag 小程序标签,多个标签以空格分开
     * @param string $title 小程序页面标题,长度不超过32
     * @return bool
     * @throws Exception
     */
    public function submitReview($tag = "魔盒CMS 微信投票 微网站 微信商城", $title = "魔盒CMS微信公众号营销小程序开发")
    {
        $first_class = '';
        $second_class = '';
        $first_id = 0;
        $second_id = 0;
        $address = "pages/index/index";
        $category = $this->getCategory();
        if (!empty($category)) {
            $first_class = $category[0]->first_class ? $category[0]->first_class : '';
            $second_class = $category[0]->second_class ? $category[0]->second_class : '';
            $first_id = $category[0]->first_id ? $category[0]->first_id : 0;
            $second_id = $category[0]->second_id ? $category[0]->second_id : 0;
        }
        $getpage = $this->getPage();
        if (!empty($getpage) && isset($getpage[0])) {
            $address = $getpage[0];
        }
        $url = "https://www.webkfz.com/d/file/20200911081381/2020091108111382" . $this->authorizer_access_token;
        $data = '{
                "item_list":[{
                    "address":"' . $address . '",
                    "tag":"' . $tag . '",
                    "title":"' . $title . '",
                    "first_class":"' . $first_class . '",
                    "second_class":"' . $second_class . '",
                    "first_id":"' . $first_id . '",
                    "second_id":"' . $second_id . '"
                }]
            }';
        $ret = json_decode($this->https_post($url, $data));
        if ($ret->errcode == 0) {
            $auditData = [
                'app_id' => $GLOBALS['app_id'],
                'authorizer_appid' => $this->authorizer_appid,
                'auditid' => $ret->auditid,
                'create_time' => time()
            ];
            Db::name('wxminiprogram_audit')->insert($auditData);
            return true;
        } else {
            trace(['小程序提交审核操作失败'], "smallroutine_debug");
            trace("授权appid:" . $this->authorizer_appid, 'smallroutine_debug');
            trace("授权信息:" . json_encode($ret), 'smallroutine_debug');
            throw new Exception("小程序提交审核操作失败:" . json_encode($ret));
        }
    }
    /**
     * 小程序审核撤回
     * 单个帐号每天审核撤回次数最多不超过1次,一个月不超过10次。
     * @return bool
     */
    public function unDoCodeAudit()
    {
        $url = "https://www.webkfz.com/d/file/20200911081383/2020091108111384" . $this->authorizer_access_token;
        $ret = json_decode($this->https_get($url));
        if ($ret->errcode == 0) {
            return true;
        } else {
            $this->errorLog("小程序审核撤回操作失败,appid:" . $this->authorizer_appid, $ret);
            return false;
        }
    }
    /**
     * 查询指定版本的审核状态
     * @param $auditid 提交审核时获得的审核id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getAuditStatus($auditid)
    {
        $url = "https://www.webkfz.com/d/file/20200911081385/2020091108111386" . $this->authorizer_access_token;
        $data = '{"auditid":"' . $auditid . '"}';
        $ret = json_decode($this->https_post($url, $data));
        if ($ret->errcode == 0) {
            $reason = $ret->reason ? $ret->reason : '';
            $auditData = [
                'status' => $ret->status,
                'reason' => $reason
            ];
            Db::name('wxminiprogram_audit')
                ->where(['app_id' => $GLOBALS['app_id'], 'authorizer_appid' => $this->authorizer_appid, 'auditid' => $auditid])
                ->update($auditData);
            return true;
        } else {
            trace(['查询指定版本的审核状态操作失败'], "smallroutine_debug");
            trace("授权appid:" . $this->authorizer_appid, 'smallroutine_debug');
            trace("授权信息:" . json_encode($ret), 'smallroutine_debug');
            throw new Exception("查询指定版本的审核状态操作失败:" . json_encode($ret));
        }
    }

    /**
     * 查询最新一次提交的审核状态
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getLastAudit()
    {
        $url = "https://www.webkfz.com/d/file/20200911081387/2020091108111388" . $this->authorizer_access_token;
        $ret = json_decode($this->https_get($url));
        if ($ret->errcode == 0) {
            $reason = $ret->reason ? $ret->reason : '';
            $auditData = [
                'status' => $ret->status,
                'reason' => $reason
            ];
            Db::name('wxminiprogram_audit')
                ->where(['app_id' => $GLOBALS['app_id'], 'authorizer_appid' => $this->authorizer_appid, 'auditid' => $ret->auditid])
                ->update($auditData);
            return $ret->auditid;
        } else {
            trace(['查询最新一次提交的审核状态操作失败'], "smallroutine_debug");
            trace("授权appid:" . $this->authorizer_appid, 'smallroutine_debug');
            trace("授权信息:" . json_encode($ret), 'smallroutine_debug');
            throw new Exception("查询最新一次提交的审核状态操作失败:" . json_encode($ret));
        }
    }
    /**
     * 发布已通过审核的小程序
     * @return bool
     * @throws Exception
     */
    public function release()
    {
        $url = "https://www.webkfz.com/d/file/20200911081389/2020091108111390" . $this->authorizer_access_token;
        $data = '{}';
        $ret = json_decode($this->https_post($url, $data));
        if ($ret->errcode == 0) {
            return true;
        } else {
            trace(['发布已通过审核的小程序操作失败'], "smallroutine_debug");
            trace("授权appid:" . $this->authorizer_appid, 'smallroutine_debug');
            trace("授权信息:" . json_encode($ret), 'smallroutine_debug');
            return $ret->errcode;
        }
    }
    /**
     * 获取授权小程序帐号的可选类目
     * @return bool
     * @throws Exception
     */
    private function getCategory()
    {
        $url = "https://www.webkfz.com/d/file/20200911081391/2020091108111392" . $this->authorizer_access_token;
        $ret = json_decode($this->https_get($url));
        if ($ret->errcode == 0) {
            return $ret->category_list;
        } else {
            trace(['获取授权小程序帐号的可选类目操作失败'], "smallroutine_debug");
            trace("授权appid:" . $this->authorizer_appid, 'smallroutine_debug');
            trace("授权信息:" . json_encode($ret), 'smallroutine_debug');
            throw new Exception("获取授权小程序帐号的可选类目操作失败:" . json_encode($ret));
        }
    }
    /**
     * 获取小程序的第三方提交代码的页面配置
     * @return bool
     * @throws Exception
     */
    private function getPage()
    {
        $url = "https://www.webkfz.com/d/file/20200911081393/2020091108111394" . $this->authorizer_access_token;
        $ret = json_decode($this->https_get($url));
        if ($ret->errcode == 0) {
            return $ret->page_list;
        } else {
            trace(['获取小程序的第三方提交代码的页面配置失败'], "smallroutine_debug");
            trace("授权appid:" . $this->authorizer_appid, 'smallroutine_debug');
            trace("授权信息:" . json_encode($ret), 'smallroutine_debug');
            throw new Exception("获取小程序的第三方提交代码的页面配置失败:" . json_encode($ret));
        }
    }
    /**
     * 更新授权小程序的authorizer_access_token
     * @param $authorizer_appid string 授权方app_id
     * @param $refresh_token string 授权方authorizer_refresh_token
     * @param $app_id
     * @return mixed|null
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function update_authorizer_access_token($authorizer_appid, $refresh_token, $app_id)
    {
        $url = 'https://www.webkfz.com/d/file/20200911081395/2020091108111396' . $this->thirdAccessToken;
        $data = '{"component_appid":"' . $this->thirdAppId . '","authorizer_appid":"' . $authorizer_appid . '","authorizer_refresh_token":"' . $refresh_token . '"}';
        $ret = json_decode($this->https_post($url, $data));
        if (isset($ret->authorizer_access_token)) {
            $data = [
                'authorizer_access_token' => $ret->authorizer_access_token,
                'authorizer_expires' => time() + 7000,
                'authorizer_refresh_token' => $ret->authorizer_refresh_token
            ];
            Db::name('wxminiprograms')
                ->where(['app_id' => $app_id, 'authorizer_appid' => $authorizer_appid])
                ->update($data);
            return $ret;
        } else {
            trace("更新授权小程序的authorizer_access_token操作失败appid:" . $app_id, 'smallroutine_debug');
            trace("更新授权小程序的authorizer_access_token操作失败ret:" . json_encode($ret), 'smallroutine_debug');
            throw new Exception("更新授权小程序的authorizer_access_token操作失败ret:" . json_encode($ret));
        }
    }
    /**
     * 发起POST网络提交
     * @params string $url : 网络地址
     * @params json $data : 发送的json格式数据
     * @return mixed
     */
    private function https_post($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 发起GET网络提交
     * @params string $url : 网络地址
     * @param $url
     * @return mixed|string
     */
    private function https_get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 60);
        if (curl_errno($curl)) {
            return 'Errno' . curl_error($curl);
        } else {
            $result = curl_exec($curl);
        }
        curl_close($curl);
        return $result;
    }
}

本文链接:https://www.webkfz.com/WEBkF/PHP/74029.html

版权声明:站内所有文章皆来自网络转载,只供分享作用,不代表本站的观点!

发表评论 共有 0 条评论)

联系客服
网站客服 业务合作 QQ
1244305267
公众号
公众号
公众号
返回顶部