微信小程序 發送模版消息


微信小程序開發之發送模板消息

1,小程序wxml頁面form表單添加 report-submit="true" 

<form bindsubmit="sub" report-submit="true">
     <button formType="submit">確認發布</button>
</form>

2,小程序js代碼 (formId唯一且只有提交表單時產生,只能使用一次)

Page({
  // 頁面的初始數據
  data: {},
  sub: function (e) {
    console.log(e.detail.formId); // 獲取formId,發送至服務器端
  }
});

3,php程序代碼

// 發送get請求
function curlGet($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    if(curl_errno($curl)){
        return 'ERROR ' . curl_error($curl);
    }
    curl_close($curl);
    return $output;
}

// 獲取小程序用戶access_token
function getToken(){
    $appid = '小程序公眾平台中的APPID'; // 注意!!!
    $appsecret = '小程序公眾平台中的APPSECRET'; // 注意!!!
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
    $output = curlGet($url);
    $result = json_decode($output, true);
    return $result['access_token'];
}
// 發送通知
function sendNotice(){
    $access_token = getToken();
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $access_token;
    $post_data = [
        'touser'           => 'openid', // 用戶的 openID,可用過 wx.getUserInfo 獲取
        'template_id'      => 'SNZQnzYFJMwwgRp3Oh2fvI_PHp_SQWqZzpiXLP3pSJI', // 小程序后台申請到的模板編號
        'page'             => '/pages/index/index', // 點擊模板消息后跳轉到的頁面,可以傳遞參數
        'form_id'          => $formid, // 第一步里獲取到的 formID
        'data'             => [
            'keyword1' => ['value' => '信息1'],
            'keyword2' => ['value' => '信息2'],
            'keyword3' => ['value' => '信息3']
        ],
        'emphasis_keyword' => '' // 需要強調的關鍵字,會加大居中顯示
    ];
    $data = json_encode($post_data, true);
    $options = [
        'http' => [
            'method'  => 'POST',
            'header'  => 'Content-type:application/json', // header 需要設置為 JSON
            'content' => $data,
            'timeout' => 60 // 超時時間
        ]
    ];
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    return $result;
}

 


免責聲明!

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



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