php 获取access_token 并生成公众号二维码
<?php
/**
* 获取access_token
* @param
* @return str
*/
public function getAccessToken()
{
$appid = 'xxxxxxxxxxx';
$secret = 'xxxxxxxxxxx';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$response = Http::get($url);
$ret = (array)json_decode($response, true);
return $ret ? $ret : [];
}
/**
* 生成带参数的二维码
* @param string $scene_str 场景值ID(字符串形式的ID),字符串类型,长度限制为1到64
* @param string $pic_name 二维码名称
* @return string
*/
public function shareCode($scene_str,$pic_name){
if(file_exists(ROOT_PATH."public/uploads/imgcode/".$pic_name.".jpg")){
return $this->getServerName()."/uploads/imgcode/".$pic_name.".jpg";
}else{
$tokenInfo = $this->getAccessToken();
$token = $tokenInfo['access_token'];
$create_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$token;
$query_data = [
'action_name'=>"QR_LIMIT_STR_SCENE",
'action_info'=>[
"scene"=>[
// "scene_str"=>'/aa/bb?id=7'
"scene_str"=>$scene_str
],
]
];
$res = Http::post($create_url,json_encode($query_data));
$res_arr = json_decode($res,true);
$showqrcode_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".UrlEncode($res_arr['ticket']);
$code_url = $res_arr['url'];
$code_image = Http::get($showqrcode_url);
$pathroot = ROOT_PATH."public/uploads/imgcode/".$pic_name.".jpg";
$dir = ROOT_PATH.'/public/uploads/imgcode/';
if(!file_exists($dir)){
mkdir($dir,0777,true);
}
$fp = fopen($pathroot, 'a');
fwrite($fp, $code_image);
fclose($fp);
return $this->getServerName()."/uploads/imgcode/".$pic_name.".jpg";
}
}
客服消息
发送图文消息(点击跳转到外链) 图文消息条数限制在1条以内,注意,如果图文数超过1,则将会返回错误码45008。
public function sendMessage(){
$event_message = file_get_contents("php://input");
$server_document = str_replace("/public","",$_SERVER['DOCUMENT_ROOT']);
libxml_disable_entity_loader(true);
$xmlstring = simplexml_load_string($event_message, 'SimpleXMLElement', LIBXML_NOCDATA);
$res = json_decode(json_encode($xmlstring),true);
if($res['Event'] == 'subscribe' || $res['Event'] == 'SCAN'){
$tokenInfo = $this->getAccessToken();
$token = $tokenInfo['access_token'];
$send_url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$token;
$picurl = $this->getUrl('/upload/pic/aa.jpg');
$description = 'descriptiontext';
$title = 'title';
$url = $res['EventKey'];
$query_data = [
"touser"=>$res['FromUserName'],
"msgtype"=>"news",
"news"=>[
"articles"=>[
[
"title"=>$title,
"description"=>$description,
"url"=>$url,
"picurl"=>$picurl,
],
],
],
];
Http::post($send_url,json_encode($query_data,JSON_UNESCAPED_UNICODE));
}
}