這篇文章主要介紹了php微信開發(fā)之二維碼生成類,本文使用微信接口實(shí)現(xiàn)二維碼的生成,并直接給出示例代碼,需要的朋友可以參考下
?
/**
* created by phpstorm.
* user: bin
* date: 15-1-16
* time: 上午9:48
*/
namespace home\common;
// 微信處理類
set_time_limit(30);
class weixin{
//構(gòu)造方法
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{
//生成臨時(shí)二維碼
$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);
}
//下載二維碼到服務(wù)器
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");
}
}
更多信息請(qǐng)查看IT技術(shù)專欄