PHP微信开发之二维码生成类
程序员文章站
2022-03-12 08:18:03
<?php /** * created by phpstorm. * user: bin * date: 15-1-16 * time: 上午9:48 */ namespace home\common; // 微信处理类 set_time_limit(30); class weixin{ //构造方法 static $qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?"; static $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&"; static $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?"; //生成二维码 public function getewm($wechatid,$fqid,$type = 1){ $wechat = m('member_public')->where(array('id'=> $wechatid))->find(); $appid = $wechat['appid']; $secret = $wechat['secret']; $access_token = $this->gettoken($appid,$secret); $url = $this->getqrcodeurl($access_token,$fqid,1); return downloadqr($url,time()); } protected function getqrcodeurl($access_token,$fqid,$type = 1){ $url = self::$qrcode_url.'access_token='.$access_token; if($type == 1){ //生成永久二维码 $qrcode= '{"action_name": "qr_limit_scene", "action_info": {"scene": {"scene_id": '.$fqid.'}}}'; }else{ //生成临时二维码 $qrcode = '{"expire_seconds": 1800, "action_name": "qr_scene", "action_info": {"scene": {"scene_id": '.$fqid.'}}}'; } $result = $this->http_post_data($url,$qrcode); $oo = json_decode($result[1]); if(!$oo->ticket){ $this->errorlogger('getqrcodeurl falied. error info: getqrcodeurl get failed'); exit(); } $url = self::$qrcode_get_url.'ticket='.$oo->ticket.''; return $url; } protected function gettoken($appid,$secret){ $access_token = file_get_contents(self::$token_url."appid=$appid&secret=$secret"); $access_token = json_decode($access_token); $access_token = $access_token->access_token; return $access_token; } protected function http_post_data($url, $data_string) { $ch = curl_init(); curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_postfields, $data_string); curl_setopt($ch, curlopt_httpheader, array( 'content-type: application/json; charset=utf-8', 'content-length: ' . strlen($data_string)) ); ob_start(); curl_exec($ch); if (curl_errno($ch)) { $this->errorlogger('curl falied. error info: '.curl_error($ch)); } $return_content = ob_get_contents(); ob_end_clean(); $return_code = curl_getinfo($ch, curlinfo_http_code); return array($return_code, $return_content); } //下载二维码到服务器 protected function downloadqr($url,$filestring){ if($url == ""){ return false; } $filename = $filestring.'.jpg'; ob_start(); readfile($url); $img=ob_get_contents(); ob_end_clean(); $size=strlen($img); $fp2=fopen('./uploads/qrcode/'.$filename,"a"); if(fwrite($fp2,$img) === false){ $this->errorlogger('dolwload image falied. error info: 无法写入图片'); exit(); } fclose($fp2); return './uploads/qrcode/'.$filename; } private function errorlogger($errmsg){ $logger = fopen('./errorlog.txt', 'a+'); fwrite($logger, date('y-m-d h:i:s')." error info : ".$errmsg."\r\n"); } }
上一篇: 那些年,我们一起误解过的REST