1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 【PHP+微信开发】之生成二维码 并扫码关注微信公众号

【PHP+微信开发】之生成二维码 并扫码关注微信公众号

时间:2018-06-23 19:29:49

相关推荐

【PHP+微信开发】之生成二维码 并扫码关注微信公众号

使用到微信接口是“生成带参数的二维码”,可以生成两种二维码,一种是临时二维码,会过期,生成量大,主要用于帐号绑定等不要求二维码永久保存的业务场景;另一种是永久二维码,没有过期时间,但生成量小(目前为最多10万个),主要用于适用于帐号绑定、用户来源统计等场景。扫码之后,如果用户没关注公众号会提示关注,如果已关注就直接进入公众号对话框。

首先创建二维码ticket,然后凭借ticket到指定URL换取二维码,具体介绍可以看官方文档微信开放文档

示例代码:

<?phpnamespace app\index\controller;use think\Controller;/*** 微信类*/class Wechat extends Controller{protected $APPID = 'xxxxxxxxxxx';protected $APPSECRET = 'xxxxxxxxxxxxxx';/*** curl请求 */public function http_curl($url, $type = 'get', $res = 'json', $arr = ''){$cl = curl_init();curl_setopt($cl, CURLOPT_URL, $url);curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false);if($type == 'post'){curl_setopt($cl, CURLOPT_POST, 1);curl_setopt($cl, CURLOPT_POSTFIELDS, $arr);}$output = curl_exec($cl);curl_close($cl);return json_decode($output, true);if($res == 'json'){if( curl_error($cl)){return curl_error($cl);}else{return json_decode($output, true);}}}/*** 获取 AccessToken*/public function getAccessToken(){$url = "https://api./cgi-bin/token?grant_type=client_credential&appid=".$this->APPID."&secret=".$this->APPSECRET;// 先判断 access_token 文件里的token是否过期,没过期继续使用,过期就更新$data = json_decode($this->get_php_file(ROOT_PATH."public".DS."wxtxt".DS."access_token.txt"));// 过期 更新if ($data->expire_time < time()) {$res = $this->http_curl($url);$access_token = $res['access_token'];if ($access_token) {// 在当前时间戳的基础上加7000s (两小时)$data->expire_time = time() + 7000;$data->access_token = $res['access_token'];$this->set_php_file(ROOT_PATH."public".DS."wxtxt".DS."access_token.txt",json_encode($data));}}else{// 未过期 直接使用$access_token = $data->access_token;}return $access_token;}// 获取存储文件中的tokenprivate function get_php_file($filename) {return trim(file_get_contents($filename));}// 把token 存储到文件中private function set_php_file($filename, $content) {$fp = fopen($filename, "w");fwrite($fp, $content);fclose($fp);}/*** 生成二维码*/public function getQrcode(){$token = $this->getAccessToken();$url = "https://api./cgi-bin/qrcode/create?access_token=$token";// 参数$param = array();$param['action_name'] = "QR_LIMIT_SCENE";$param['action_info'] = array( 'scene' => array( 'scene_id'=>'123' ) );$param = json_encode($param);// 返回二维码的ticket和二维码图片解析地址$res = $this->http_curl($url, 'post', 'json', $param);// 通过ticket换取二维码$qrcode = "https://mp./cgi-bin/showqrcode?ticket=".$res['ticket'];//输出二维码图片路径echo "<center><img src=".$qrcode."></center>"; }}

运行getQrcode()方法,效果如下

思路说明:

1.获取Token,注意过期时间

2.获取ticket,拿Token和二维码的一些参数,换取ticket

3.生成二维码,拿ticket换取二维码地址

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。