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"}"

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM