PHP实现生成二维码的示例代码 |
前言为了满足用户渠道推广分析和用户账号绑定等场景的需要,公众平台提供了生成带参数二维码的接口 。使用该接口可以获得多个带不同场景值的二维码,用户扫描后,公众号可以接收到事件推送 。 1、目前有2种类型的二维码
2、用户扫描带场景值二维码时,可能推送以下两种事件
获取带参数的二维码的过程包括两步,首先创建二维码ticket,然后凭借ticket到指定URL换取二维码 。 3、创建二维码ticket每次创建二维码ticket需要提供一个开发者自行设定的参数(scene_id),分别介绍临时二维码和永久二维码的创建二维码ticket过程 。 4、临时二维码请求说明http请求方式: POST URL: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN POST数据格式:json POST数据例子:{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}} 或者也可以使用以下POST数据创建字符串形式的二维码参数: {"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "test"}}} 5、永久二维码请求说明http请求方式: POST URL: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN POST数据格式:json POST数据例子:{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}} 或者也可以使用以下POST数据创建字符串形式的二维码参数: {"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "test"}}} 6、临时二维码和永久二维码生成实现的代码//临时二维码 public function getQrls() { $accessToken = $this->_getWxAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$accessToken}"; $postArr = [ "action_name" => "QR_SCENE", "expire_seconds" => 604800, "action_info" => [ 'scene' => ['scene_id' => 2000], ], ]; $postJson = json_encode($postArr); $res = $this->ch($url, 'post', 'json', $postJson); $ticket = $res['ticket']; $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket); echo "<img src='".$url."'>"; } //永久二维码 public function getQryj() { $accessToken = $this->_getWxAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$accessToken}"; $postArr = [ "action_name" => "QR_LIMIT_SCENE", "action_info" => [ 'scene' => ['scene_id' => 3000], ], ]; $postJson = json_encode($postArr); $res = $this->ch($url, 'post', 'json', $postJson); $ticket = $res['ticket']; $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket); echo "<img src='".$url."'>"; } //url请求 private function ch($url, $type='get', $res='json', $arr='') { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); if ($type == 'post') { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $arr); } $cnt = curl_exec($ch); if (curl_errno($ch)) { return; } curl_close($ch); if ($res == 'json') { return json_decode($cnt, true); } return $cnt; } 生成临时、永久二维码的图片这里就不放了,感兴趣的可以自己运行一下哈 。 到此这篇关于PHP实现生成二维码的示例代码的文章就介绍到这了,更多相关PHP生成二维码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持! |