以下是一个简单的PHP代码示例,用于通过微信公众号发送图片:

<?php
// 微信公众号的appid和appsecret
$appid = "your_appid";
$appsecret = "your_appsecret";

// 获取access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
$result = file_get_contents($url);
$json = json_decode($result, true);
$access_token = $json["access_token"];

// 上传图片并获取media_id
$file_path = "path/to/image.jpg";
$url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=image";
$file_data = array("media" => new CURLFile(realpath($file_path)));
$result = curl_post($url, $file_data);
$json = json_decode($result, true);
$media_id = $json["media_id"];

// 发送图文消息
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
$data = array(
    "touser" => "openid",
    "msgtype" => "image",
    "image" => array("media_id" => $media_id)
);
$result = curl_post($url, json_encode($data));

// 输出结果
var_dump($result);

// CURL POST请求
function curl_post($url, $data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
?>

注意:在使用此示例代码之前,您需要将$appid$appsecret替换为您自己的微信公众号的appid和appsecret,并将$file_path替换为您要上传的图像的路径。另外,您需要确保服务器上已安装CURL扩展。

php写一个微信公众号发送图片的代码

原文地址: https://www.cveoy.top/t/topic/LrU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录