一.微信消息接收消息
1.yii2中接收token验证及事件处理
$echostr = Yii::$app->request->get('echostr', '');
//微信服务器发来的验证
if (!empty($echostr)) {
// 验证来源
if ($this->checkSignature()) {
print_r($echostr);
}
} else {
//用户发来的消息处理
$this->responseMsg();
}
Yii::$app->end();
/**
* 验证微信服务器
* @return bool
*/
public function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = 'token';
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if ($tmpStr == $signature) {
return true;
} else {
return false;
}
}
2.微信事件处理
public function responseMsg()
{
$postStr = file_get_contents("php://input");
if (!empty($postStr)) {
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$form_MsgType = $postObj->MsgType;
// 事件消息
if ($form_MsgType == "event") {
// 获取事件类型
$form_Event = $postObj->Event;
if ($form_Event == "subscribe") {
// 关注
if (!empty($postObj->Ticket)) {
// 扫二维码关注
} else {
// 自然关注
}
}elseif ($form_Event == "unsubscribe") {
// 取关
echo "";
}
}
} else {
echo "";
}
}
3.生成带二维码图片
/**
* 缩放图片
* @param $src_file
* @param float $per
* @return resource
*/
public static function thrum($src_file, $per)
{
$filename = $src_file;
list($width, $height) = getimagesize($filename);
$n_w = $width * $per;
$n_h = $height * $per;
$new = imagecreatetruecolor($n_w, $n_h);
$img = imagecreatefromjpeg($filename);
imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
return $new;
}
/**
* 合成图片
* @param $path1
* @param $path2
* @param $x
* @param $y
* @param $per
* @return string
*/
public static function compose($path1, $path2, $x, $y, $per)
{
$path_1 = $path1;
$path_2 = str_replace('https', 'http', $path2); // 无配置ssl的环境不能解析https,如有需要需强转成http
$image_1 = imagecreatefrompng($path_1); // 获取图片
$image_2 = self::thrum($path_2, $per); // 压缩图片
imagecopymerge($image_1, $image_2, $x, $y, 0, 0, imagesx($image_2), imagesy($image_2), 100); // 合成到image1
$fileName = uniqid() . time() . rand(1000, 9999) . '.png'; // 生成唯一图片名
$savePath = \Yii::$app->getRuntimePath() . '/' . $fileName; // 生成地址
imagepng($image_1, $savePath); // 保存本地
return $savePath;
}
$savePath = GdHelper::compose('底图', '插入图', '距左距离', '距上距离', '压缩比例');
$file = new \CURLFile($savePath, 'image/png', $savePath); // 获取图片文件
$params = [
'access_token' => 'access_token',
'type' => 'image',
'media' => $file
];
$curl = new Curl();
$this->startTime = Dh::microtimeFloat(); //Request Begin
$response = $curl
->setHeaders([
"content-type" => "multipart/form-data"
])
->setRawPostData($params)
->setOptions([
CURLOPT_TIMEOUT => 5
];)
->post('https://api.weixin.qq.com/cgi-bin/media/upload'); // 上传微信
$this->afterRequest($curl);
$media_id = $response['media_id']; // 获取素材id