微信发送下拉模板

第一步,我们先封装好curl:

//封装curl
function http_curl($url, $type = 'get', $res = 'json', $arr = '') {
	//初始化curl
	$ch = curl_init();
	//设置curl参数
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	if ($type == 'post') {
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
	}
	//采集
	$output = curl_exec($ch);
	//关闭
	//curl_close($ch);
	if ($res == 'json') {
		if (curl_errno($ch)) {
			//请求失败,返回错误信息
			return curl_error($ch);
		} else {
			//请求成功
			return json_decode($output, true);
		}
	}
}

第二步,获取到token:

function getwxaccess_token(){
        $appid  = "xxxxxxxxxxx";
        $secret = "xxxxxxxxxxxx";
        $url    = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = json_decode(curl_exec($ch), true);
		curl_close($ch);
		return $res['access_token'];
}

第三步,开始调用封装好的模板下发:

// $toUser用户openid  $template_id模板下发id  $durl跳转地址  $data模板内容
function sendWxTampaleMsgUrl($touser, $template_id, $durl, $data) {
	//1.获取微信access_token
	$access_token = getwxaccess_token();
	$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
	//2.创建消息数组
	$tamp = array(
		'touser' => "{$touser}",
		'template_id' => $template_id,
		'url' => $durl,
		'topcolor' => "#FF0000",
		'data' => $data,
	);

	//3.转成json
	$tampJson = urldecode(json_encode($tamp));
	//4.请求接口
	$res = http_curl($url, 'post', 'json', $tampJson);
	return $res;
}

注意事项:

1. 方法为封装,可拿去调取;

2. TP框架需要加public及$this;

3. return返回数组报错可用return json($res);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值