公众号推送小程序卡片

首先公众号需要开通客服功能,没有的在公众号插件里添加

//验证signature
/*
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$echostr=$_GET["echostr"];
$token = "TOKEN"; //这里个token 需要跟公众号配置的一直才能通过验证 ,验证通过就可以注释掉了
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if ($tmpStr == $signature ) {
    return $echostr;
} else {
    ErrorLogger($echostr);
    return false;
}
*/

 $xml = file_get_contents('php://input');
 $postArr = fromXml($xml);
 $accessToken = getAccessToken();
 $thumb_media_id = '-sVDfOirXgF1yzlwqD1i2RrkZal1wjxtSaChPmF2f_nVFos0qrVm1GRVB0fJtyh-99'; //生成方法https://blog.csdn.net/u013071763/article/details/115264560
 
 $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $accessToken;
 $data['touser'] = $postArr['FromUserName'];
 $data['msgtype'] = "miniprogrampage";
 $data['miniprogrampage'] = [
  "title" => "Hello World",
  "pagepath" => "pages/index/index?foo=bar",
  "appid" =>"xxxx",
  "thumb_media_id"=>$thumb_media_id 
  ];
 $json = json_encode($data, JSON_UNESCAPED_UNICODE);
 $res = postCurlWxapp( $url,$json);


function getAccessToken(){
    
    $appid = 'xx';
    $srcret = 'xx';
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$srcret;
	$data= getCurlWxapp($url);
	$data = json_decode($data,true);
	return $data["access_token"];

		
}

function postCurlWxapp($url,$data){
	$ch = curl_init();
	$header = "Accept-Charset: utf-8";
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$tmpInfo = curl_exec($ch);
	if(curl_errno($ch)){
		return false;
	}else{
		return $tmpInfo;
	}
}


/**
 * 将xml转为array
 * @param $xml
 * @return mixed
 */
 function fromXml($xml)
{
    // 禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}



参考
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#6

上一篇:PHP中使用curl获取头信息headers的一些笔记


下一篇:PHP用CURL发送Content-type为application/json的POST请求方法