<?php
/*
* 图片上传API(demo php版本)
* 文档地址:https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/marketing/chapter3_1.shtml
* */
//生成signature
//HTTP请求方法\r\n
//URI\r\n
//请求时间戳\r\n
//请求随机串\r\n
//请求报文\r\n
//这里设置您的图片文件名,要绝对路径
$file_name = "/home/users/logo.png";
$file_content = file_get_contents($file_name); //图片二进制
$HTTP_METHOD = "POST";
$URI="/v3/marketing/favor/media/image-upload";
$TIMESTAMP = time(); //保证最新
$NONSTR = ''; //请求唯一标识,请商户自行生成(必须填写)
$sp_mchid = ''; //商户号(必须填写)
$serial_no = ''; //证书序列号(必须填写)
$MCHPRIKEYSTR = "-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----"; //商户私钥(必须填写)
//生成图片meta信息
$meta = str_replace(array("FILENAME", "SHA256"), array($file_name, hash("sha256", $file_content)), "{\"filename\":\"FILENAME\",\"sha256\":\"SHA256\"}");
//生成签名
$raw_str = $HTTP_METHOD."\n".$URI."\n".$TIMESTAMP."\n".$NONSTR."\n".$meta."\n"; //签名原串
$prikey = openssl_pkey_get_private($MCHPRIKEYSTR);
$algo = "sha256WithRSAEncryption";
openssl_sign($raw_str, $signature, $prikey, $algo);
openssl_free_key($prikey);
$final_sign = base64_encode($signature); //最终签名base64encode
//拼接请求body
$post_body = "--eklfile\r\nContent-Disposition:form-data;name=\"meta\"\r\nContent-Type:application/json\r\n\r\n".$meta."\r\n--eklfile\r\nContent-Disposition:form-data;name=\"file\";filename=\"".$file_name."\"\r\nContent-Type:image/jpg\r\n\r\n". $file_content."\r\n--eklfile--\r\n";
//请求头Authorization信息
$authorization = 'WECHATPAY2-SHA256-RSA2048 mchid="SPMCHID",nonce_str="NONSTR",signature="SIGNATURE",timestamp="TIMESTAMP",serial_no="SERIAL_NO"';
$authorization = str_replace(array("SPMCHID", "NONSTR", "SIGNATURE", "TIMESTAMP", "SERIAL_NO"), array($sp_mchid, $NONSTR, $final_sign, $TIMESTAMP, $serial_no), $authorization);
$URL = "https://api.mch.weixin.qq.com".$URI;
function curl_post($url, $body, $headers)
{
$ch = curl_init();
$timeout = 300;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
//注意,使用curl方法,必须制定content内容为二进制转化
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$handles = curl_exec($ch);
curl_close($ch);
return $handles;
}
$headers = [
'Accept:application/json',
'Authorization:'.$authorization,
'Content-Type:multipart/form-data;boundary=eklfile',
'User-Agent:CURL/7.54.0'
];
$res = curl_post($URL, $post_body, $headers);
var_dump($res);
exit;
微信营销图片上传API Demo
最新推荐文章于 2022-05-27 17:21:15 发布