<?php
namespace utils;
class Wechat
{
private function getAccessToken()
{
$appid = config('wechat.appId');
$appsecret = config('wechat.secret');
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
$res = json_decode(file_get_contents($url),true);
if (isset($res['errcode']) && $res['errcode']) {
$this->redirect('getCode');
}
return $res["access_token"];
}
private function getTicket($sceneid, $type='temp', $expire_seconds=604800){
if($type=='temp'){
$data = '{"expire_seconds": %s, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": %s}}}';
$data = sprintf($data,$expire_seconds,$sceneid);
}else{
$data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": %s}}}';
$data = sprintf($data,$sceneid);
}
$url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->getAccessToken();
$content = $this->post_json_data($url, $data);
$cont = json_decode($content);
return $cont->ticket;
}
public function getQRCode($sceneid, $type='temp', $expire_seconds=604800){
$ticket = $this->getTicket($sceneid, $type, $expire_seconds);
$url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.urlencode($ticket);
return $url;
}
private function post_json_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);
$return_content = ob_get_contents();
ob_end_clean();
return $return_content;
}
}