想要让用户提交表单后发送一条模板消息给用户,首先需要在小程序表单标签里加上report-submit参数,如: ~~~ <form bindsubmit="formSubmit" report-submit="true"> <view class="btn-area"> <button formType="submit">发个模板消息</button> </view> </form> ~~~ 然后在表单提交后端服务器时带上参数formId和openid ~~~ formSubmit: function (e) { var formId = e.detail.formId wx.request({ url: app.url + 'Api/Api/send_message&PHPSESSID=' + wx.getStorageSync('PHPSESSID'), data: { formId: formId, openid: wx.getStorageSync('openid') }, success: function (res) { // success console.log(res) } }) }, ~~~ 最后在后端PHP服务器发起一个模板消息请求。其中模板ID参数(template_id)就是我们上一节 [消息模板配置](消息模板配置.md) 里增加的模板ID,而data里的keyword参数个数需要与您配置的模板里的参数一一对应。 ~~~ function send_message() { // 发送模板消息给用户 $openid = I ( 'openid' ); $formId = I ( 'formId' ); $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_access_token (); $param ['touser'] = $openid; $param ['template_id'] = '-ekG5kJ-8x7OkTxd1shG-5-y90q8El5vj0DKVGwTZ9o'; $param ['form_id'] = $formId; $param ['data'] = [ 'keyword1' => [ 'value' => '1706261498468955374', 'color' => '#173177' ], 'keyword2' => [ 'value' => '1.00元', 'color' => '#173177' ], 'keyword3' => [ 'value' => '2017-05-25 14:30', 'color' => '#173177' ], 'keyword4' => [ 'value' => '梦云商城-服务购买', 'color' => '#173177' ], 'keyword5' => [ 'value' => '已完成支付', 'color' => '#173177' ], 'keyword6' => [ 'value' => '微信支付', 'color' => '#173177' ] ]; $res = post_data ( $url, $param ); echo json ( $res ); } ~~~ >[warning] 注意:由于开发者工具里的formId只是一个模拟值,不正确的,因此在开发者工具里无法发起消息模板,必须要使用手机预览里只能正常