PHP 小程序发模板消息

记录一下DEMO

<?php

function getAccessToken ($appid, $appsecret) {                  
  $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
  $html = file_get_contents($url);
  $output = json_decode($html, true);
  $access_token = $output['access_token'];

  return $access_token;
}

// 根据你的模板对应的关键字建立数组
// color 属性是可选项目,用来改变对应字段的颜色
$value = '为什么会这样测试';
$color = '#FF0000';
$data_arr = array(
  'keyword1' => array( "value" => $value, "color" => $color ),
  'keyword2' => array( "value" => $value, "color" => $color ),
  'keyword3' => array( "value" => $value, "color" => $color ),
  'keyword4' => array( "value" => $value, "color" => $color )
);

$openid = 'onRuB4nGLMDTXUV-mxhlYOgV0nuY';
$templateid = 'UHttQpo6ZTkRgP93JWHmG7ChUm2aL9BCU5vzplCEtd0';
$formid = '339f1696b1544e87b3811433179f7910';
$post_data = array (
  // 用户的 openID,可用过 wx.getUserInfo 获取
  "touser"           => $openid,
  // 小程序后台申请到的模板编号
  "template_id"      => $templateid,
  // 点击模板消息后跳转到的页面,可以传递参数
  "page"             => "/pages/app/init/main",
  // 第一步里获取到的 formID
  "form_id"          => $formid,
  // "prepay_id"          => $formid,
  // 数据
  "data"             => $data_arr,
  // 需要强调的关键字,会加大居中显示
  "emphasis_keyword" => "keyword2.DATA"

);
        
// 发送 POST 请求的函数
// 你也可以用 cUrl 或者其他网络库,简单的请求这个函数就够用了         
function send_post( $url, $post_data ) {
  $options = array(
    'http' => array(
      'method'  => 'POST',
      // header 需要设置为 JSON
      'header'  => 'Content-type:application/json',
      'content' => $post_data,
      // 超时时间
      'timeout' => 60
    )
  );

  $context = stream_context_create( $options );
  $result = file_get_contents( $url, false, $context );

  return $result;
}

// 这里替换为你的 appID 和 appSecret
$appid = 'xxxx';
$appsecret = 'xxx';
$url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".getAccessToken ($appid, $appsecret);  
// 将数组编码为 JSON
$data = json_encode($post_data, true);   

// 这里的返回值是一个 JSON,可通过 json_decode() 解码成数组
$return = send_post( $url, $data);
var_dump($return);

成功返回:

string(27) "{"errcode":0,"errmsg":"ok"}"

同时微信上也会收到模板消息

原文地址:https://www.cnblogs.com/xiangsj/p/10932682.html