微信小程序订阅功能

  • 前端订阅按钮

1.微信开发者工具前端按钮

 // wxml
<button class="cuIcon-subscription" style="width:28%" bindtap="book">订阅</button>

2.发送request

模板号在官方网页找: https://mp.weixin.qq.com/wxamp/newtmpl/tmpllib?start=0&limit=10&token=205493114&lang=zh_CN

 // js
  book(e){
    var openid=this.data.openid
    var gameid=this.data.gameID
    wx.requestSubscribeMessage({
      tmplIds: ['模板号'],
      success (res) { 
        wx.request({
            url: 'api地址',   
            data:{
              'tmplIds':'模板号',        
              'openid':openid,
              'gameid':gameid,
            },     
            success:(res)=>{
              console.log("accessToken"+res)
            }
        })
      }
    })
  },

3.API接收参数

 # app.py    
def main(req: func.HttpRequest) -> func.HttpResponse:
     gameid = req.params.get('gameid')
    openid = req.params.get('openid')
    tmplIds = req.params.get('tmplIds')

4.将值存入数据库

找到数据库中的对应事件

# app.py
cnx = mysql.connector.connect(user="", password='', host="", port=3306, database='',  ssl_verify_cert=False)
    cursor = get_cursor(cnx)
    cursor.execute(
        'SELECT * FROM gameListjson where gameid = %s',(gameid,)
        
    )
    result = cursor.fetchall()

更新postInfo

    if len(result) == 0:
        cursor.close()
        cnx.close()
        return func.HttpResponse(  (json.dumps(result) +"GameID doesn't exist." ))

    else:
        logging.info(result[0]['postInfo'] )
                    
        postInfo =  json.loads(result[0]['postInfo'])
                data={
            'tmplIds':tmplIds,        
            'openid':openid,
        }
     
        postInfo.append(data)
                
        




        cursor.execute(
                    'UPDATE gameListjson SET postInfo = %s '
                    ' WHERE gameid = %s',
                    ( json.dumps(postInfo), gameid)
                )
        cnx.commit()
    
        
        cursor.close()
        cnx.close()

        return func.HttpResponse(json.dumps(postInfo))

需要调用的函数

def get_cursor(cnx):
    cursor = cnx.cursor(buffered=True,dictionary=True)
    return cursor
  • 发送订阅信息

1.微信开发者工具调用函数

 // js
sendMessage(){
    var gameID =   this.data.currentGameInfo.gameID
    wx.request({
      url: 'api地址', 
      data: { 
          'gameid':gameID,
      },
     
      success(res) {
        console.log("res",res)
      },
      fail(error){
        console.log("error",error)
      }
    })
  },

2.拿access_token

# app.py
def main(req: func.HttpRequest) -> func.HttpResponse:
    #获取access_token
    appid = ''
    appsecret = ''
    payload = {
      'appid': appid,
      'secret': appsecret,    
      'grant_type':'client_credential',     
       }
    r = requests.get('https://api.weixin.qq.com/cgi-bin/token',params=payload)
    logging.info(r.text)
    logging.info(r.json())
    resJSON= r.json()
    access_token=resJSON['access_token']
    logging.info(access_token)

3.读数据库信息

# app.py
       gameid = req.params.get('gameid')
    logging.info(gameid)

    
     
    data_response={
        'gameid':gameid,
    }
    
    #读取订阅
    cnx = mysql.connector.connect(user="", password='', host="", port=3306, database='',  ssl_verify_cert=False)
    cursor = get_cursor(cnx)
    cursor.execute(
        'SELECT * FROM gameListjson where gameid = %s',(gameid,)
        
    )
    result = cursor.fetchall()

4.生成和发送模板信息

# app.py
       gameInfo = json.loads(result[0]['gameInfo'])

    date = gameInfo['date']
    year = int(str(date)[0:4])
    month = int(str(date)[4:6])
    day = int(str(date)[6:8])
    balls = gameInfo['balls']
    value1 = str(month)+"月"+str(day)+"日"+balls
    signedPlayers = gameInfo['signedPlayers']
    if len(result) == 0:
        cursor.close()
        cnx.close()
        return func.HttpResponse(  (json.dumps(result) +"gameid doesn't exist." ))

    else:
      
        postInfo = json.loads(result[0]['postInfo'])
        logging.info(postInfo)
      
        for i in  postInfo:
            #发送消息
            data={
                "touser": i['openid'],
                "template_id": "AgVuUKgxlF9DV3EOGAyKbv_grx7NtkrjO5tjNYQI-Fc",
                "data":{
                  "thing1": {
                    "value": value1
                  },
                  "thing2": {
                    "value": "有新的人报名"
                  },
                  "thing3": {
                    "value": "现在共"+str(signedPlayers)+"人约球"
                  }
                  
                }
              }
            payload2 = {
              'access_token': access_token
            }  
            p = requests.post('https://api.weixin.qq.com/cgi-bin/message/subscribe/send',params=payload2,data=json.dumps(data))
            logging.info(p.url)
            logging.info(p.text)

        
        cnx.commit()           
        cursor.close()
        cnx.close()
    
    
    return func.HttpResponse(access_token)

需要调用的函数

def get_cursor(cnx):
    cursor = cnx.cursor(buffered=True,dictionary=True)
    return cursor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值