因爲我錄製過一個小程序的課程,裏面有消息模板的講解。最近有幾位同窗反饋 官方要 取消消息模板,使用訂閱消息。爲了方便你們容易學 Python Flask構建微信小程序訂餐系統 課程。我把訂閱消息結合這個課程講解下如何實現php
其實對於咱們來說,對接第三方無非就是接口地址換了,或者流程上作一些調整。好,廢話少說咱們直接來經過實戰講解如何對接 訂閱消息html
對接任何東西必然要先了解這個東西是什麼?流程是什麼樣的?官方文檔地址:點擊這裏傳送門。python
主要步驟就是 申請模板、獲取發送權限、後端調用api發送。其中和模板消息最大的區別 就是要獲取下發權限,這是最大的區別。也就是這個權限控制在用戶手中了。git
這一步就須要有個界面明確讓用戶訂閱消息,若是用戶拒絕 就不能給用戶發送消息了。須要改一下咱們課程的小程序。對應API地址:點擊這裏傳送門。web
那咱們來修改咱們支付相關的代碼。修改記錄 總共須要修改三個文件express
mina/pages/my/order_list.js toPay:function( e ){ var that = this; //這裏增長獲取用戶訂閱消息權限,須要將申請的模板id填寫進來。這裏填寫你本身的 var template_ids = ["gEWJzj_7_7bBej8grUY7V3ZWLLYU2sIp2jNSO5w2Fos" ]; //默認不能發送消息,當用戶明確選擇了容許才能夠發. var can_send = 0; var data = { order_sn: e.currentTarget.dataset.id, can_send: can_send }; wx.requestSubscribeMessage({ tmplIds: template_ids, success:function( res ){ for (var tmp_id of template_ids ){ if (res.hasOwnProperty(tmp_id) && res[tmp_id] == "accept"){ can_send = 1; } } data['can_send'] = can_send; //成功調用支付下單 that.doPay( data ); }, fail:function( res ){ //失敗調用支付下單 that.doPay(data); } }); }, doPay:function( data ){ //新增長的方法 wx.request({ url: app.buildUrl("/order/pay"), header: app.getRequestHeader(), method: 'POST', data: data, success: function (res) { var resp = res.data; if (resp.code != 200) { app.alert({ "content": resp.msg }); return; } var pay_info = resp.data.pay_info; wx.requestPayment({ 'timeStamp': pay_info.timeStamp, 'nonceStr': pay_info.nonceStr, 'package': pay_info.package, 'signType': 'MD5', 'paySign': pay_info.paySign, 'success': function (res) { }, 'fail': function (res) { } }); } }); }
web/controllers/api/Order.py:orderPay 最後幾行 #保存prepay_id爲了後面發模板消息 ''' 若是對接了訂閱消息,這個prepay_id 就沒有用了 爲了節省一個字段,就用這個自動存放 能不能發送吧 ''' #pay_order_info.prepay_id = pay_info['prepay_id'] pay_order_info.prepay_id = req['can_send'] if 'can_send' in req else 0 db.session.add( pay_order_info ) db.session.commit() resp['data']['pay_info'] = pay_info return jsonify(resp)
jobs/tasks/queue/index.py def handlePay(self,item ): data = json.loads( item.data ) if 'member_id' not in data or 'pay_order_id' not in data: return False oauth_bind_info = OauthMemberBind.query.filter_by(member_id=data['member_id']).first() if not oauth_bind_info: return False pay_order_info = PayOrder.query.filter_by( id = data['pay_order_id']).first() if not pay_order_info: return False #更新銷售總量 pay_order_items = PayOrderItem.query.filter_by( pay_order_id = pay_order_info.id ).all() notice_content = [] if pay_order_items: date_from = datetime.datetime.now().strftime( "%Y-%m-01 00:00:00" ) date_to = datetime.datetime.now().strftime( "%Y-%m-31 23:59:59" ) for item in pay_order_items: tmp_food_info = Food.query.filter_by( id = item.food_id ).first() if not tmp_food_info: continue notice_content.append( "%s %s份"%( tmp_food_info.name,item.quantity) ) #當月數量 tmp_stat_info = db.session.query(FoodSaleChangeLog, func.sum(FoodSaleChangeLog.quantity).label("total")) \ .filter( FoodSaleChangeLog.food_id == item.food_id )\ .filter( FoodSaleChangeLog.created_time >= date_from,FoodSaleChangeLog.created_time <= date_to ).first() tmp_month_count = tmp_stat_info[ 1 ] if tmp_stat_info[ 1 ] else 0 tmp_food_info.total_count += 1 tmp_food_info.month_count = tmp_month_count db.session.add( tmp_food_info ) db.session.commit() if pay_order_info.prepay_id != "1": #當prepay_id == 1表示用戶接受發訂閱消息 app.logger.info("skip notice~~") return ##發訂閱消息 keyword1_val = pay_order_info.order_number keyword2_val = "、".join( notice_content ) keyword3_val = "總價:" + str( pay_order_info.total_price ) if pay_order_info.express_info: express_info = json.loads( pay_order_info.express_info ) keyword3_val += "快遞信息:" + str( express_info['address'] ) #發送模板消息 target_wechat = WeChatService( ) access_token = target_wechat.getAccessToken() headers = {'Content-Type': 'application/json'} url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s"%access_token params = { "touser": oauth_bind_info.openid, "template_id":"gEWJzj_7_7bBej8grUY7V3ZWLLYU2sIp2jNSO5w2Fos", "page": "pages/my/order_list", "data": { "number1": { "value": keyword1_val }, "thing2": { "value": keyword2_val }, "thing3": { "value": keyword3_val } } } r = requests.post(url=url, data= json.dumps( params ).encode('utf-8'), headers=headers) r.encoding = "utf-8" app.logger.info(r.text) return True
課程官方已經上傳對應的源碼補丁包:點擊這裏傳送門json