PHP 小程序發模板消息

記錄一下DEMOphp

<?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);

 

成功返回:html

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

同時微信上也會收到模板消息小程序

相關文章
相關標籤/搜索