微信小程序集中开发日志 DAY 3 【生成小程序二维码 + 缓存小程序access_token】

上一章  微信小程序集中开发日志 DAY 2 【data的赋值与取值 + 跳转页面】

目录

生成小程序二维码

缓存小程序access_token


生成小程序二维码

当然了,只有正式上线的小程序才可以生二维码,测试的时候就用测试接口好了。

1.准备

①小程序的appid和appsecret

②微信公众平台接口调试工具 

③测试接口插件一枚

2.获取小程序测试access_token  

微信公众平台调试工工具

 这access_token就是测试用的,实际项目中无效

3.测试接口跑一下

 这边我用的是火狐的RESTClient

①提交方式 post

②HTTP响应类型 图文型Blob

③接口地址 https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=

access_token就填刚刚在调试工具里面获取到的值

④body里面填 {"path":"pages/index?rid=1","width",430}

其中path表示此二维码需要展示的小程序的页面,该路径需要在小程序的 app.json 的 pages 中定义

路径后面可以设置参数,参数间用&符号隔开,path值的最大长度 128 字节 
width表示二维码的宽度 

 然后点击发送,就可以在RESTClient中预览到二维码了

 

缓存小程序access_token

和公众号一样也是两小时过期,2000次的上限

 

access_token.php

创建一个类,memcache两小时缓存一次token

class class_weixin
{
    var $appid = '';
    var $appsecret = '';

    //构造函数,获取Access Token
    public function __construct($appid = NULL, $appsecret = NULL)
    {
        if($appid && $appsecret){
            $this->appid = $appid;
            $this->appsecret = $appsecret;
        }

        //本地环境,需已安装memcache
        $_MEMC = new Memcache;
        $_MEMC->connect('localhost', 11211) or die ("Could not connect");

        $this->access_token = $_MEMC->get($this->appid);
        if (!isset($this->access_token) || empty($this->access_token)){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $res = $this->http_request($url);
            $result = json_decode($res, true);
            $this->access_token = $result["access_token"];
            $_MEMC->set($this->appid, $this->access_token, 0, 3600);
        }
        
        return $this->access_token;
    }

    protected function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}

下一章  微信小程序集中开发日志 DAY 4 【图片上传】

猜你喜欢

转载自blog.csdn.net/qq_41654694/article/details/86517818