def orderPay(): resp = {'code': 200, 'msg': '操作成功', 'data': {}} member_info = g.member_info req = request.values order_sn = req['order_sn'] if 'order_sn' in req else '' # 判断订单信息是否存在 pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() if not pay_order_info: resp['code'] = -1 resp['msg'] = '系统繁忙,稍后再试-1' return jsonify(resp) # 为了取出openid的值 oauth_bind_info = OauthMemberBind.query.filter_by(member_id=member_info.id).first() if not oauth_bind_info: resp['code'] = -1 resp['msg'] = '系统繁忙,稍后再试-2' # 为了防止钓鱼网站,不给出具体提示信息 return jsonify(resp) # 设置回调地址 重要************** config_mina = app.config['MINA_APP'] notify_url = 'http://120.78.170.188:8666' + config_mina['callback_url'] app.logger.info(notify_url) # 创建对象,引入微信下单的方法 target_wechat = WeChatService(merchant_key=config_mina['paykey']) # 获取sign 签名的方法,需要传递这些数据 data = { 'appid':config_mina['appid'], 'mch_id':config_mina['mch_id'], 'nonce_str':target_wechat.get_nonce_str(), 'body':'订餐', 'out_trade_no': pay_order_info.order_sn, 'total_fee':int( pay_order_info.total_price * 100 ), 'notify_url':notify_url, 'trade_type':'JSAPI', 'openid':oauth_bind_info.openid } # 重要操作: 1.生成签名 2.拼接数据转成xml格式 通过post方式发送为微信服务器,得到响应数据 pay_info = target_wechat.get_pay_info(data) # 保存prepay_id为了后面发模板消息,prepay_id为第三方预付id pay_order_info.prepay_id = pay_info['prepay_id'] db.session.add(pay_order_info) db.session.commit() resp['data']['pay_info'] = pay_info return jsonify(resp)
def orderCallback(): result_data = {'return_code': 'SUCCESS', 'return_msg': 'OK'} header = {'Content-Type': 'application/xml'} config_mina = app.config['MINA_APP'] target_wechat = WeChatService(merchant_key=config_mina['paykey']) callback_data = target_wechat.xml_to_dict(request.data) app.logger.info(callback_data) sign = callback_data['sign'] callback_data.pop('sign') gene_sign = target_wechat.create_sign(callback_data) app.logger.info(gene_sign) if sign != gene_sign: result_data['return_code'] = result_data['return_msg'] = "FAIL" return target_wechat.dict_to_xml(result_data), header if callback_data['result_code'] != 'SUCCESS': result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header order_sn = callback_data['out_trade_no'] pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() if not pay_order_info: result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header if int(pay_order_info.total_price * 100) != int( callback_data['total_price']): result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header if pay_order_info.status == 1: return target_wechat.dict_to_xml(result_data), header target_pay = PayService() target_pay.orderSuccess(pay_order_id=pay_order_info.id, params={'pay_sn': callback_data['transaction_id']}) # 将微信回调的结果放入记录表 target_pay.addPayCallbackData(pay_order_id=pay_order_info.id, data=request.data) return target_wechat.dict_to_xml(result_data), header
def orderPay(): resp = {'code': 200, 'msg': '操作成功', 'data': {}} member_info = g.member_info req = request.values order_sn = req['order_sn'] if 'order_sn' in req else '' pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() if not pay_order_info: resp['code'] = -1 resp['msg'] = "系统繁忙,请稍后再试" return jsonify(resp) oauth_bind_info = OauthMemberBind.query.filter_by( member_id=member_info.id).first() if not oauth_bind_info: resp['code'] = -1 resp['msg'] = "系统繁忙,请稍后再试" return jsonify(resp) config_mina = app.config['MINA_APP'] notify_url = app.config['APP']['domain'] + config_mina['callback_url'] target_wechat = WeChatService(merchant_key=['paykey']) data = { "appid": config_mina['appid'], "mch_id": config_mina['mch_id'], "nonce_str": target_wechat.get_nonce_str(), "body": "购书", "out_trade_no": pay_order_info.order_sn, "total_fee": int(pay_order_info.total_price * 100), "notify_url": notify_url, "trade_type": "JSAPI", "openid": oauth_bind_info.openid } pay_info = target_wechat.get_pay_info(data) # 保存prepay_id为了后面发模板消息 # 没有注册商家用户无prepay_id if pay_info['prepay_id']: pay_order_info.prepay_id = pay_info['prepay_id'] db.session.add(pay_order_info) db.session.commit() resp['data']['pay_info'] = pay_info return jsonify(resp)
def orderCallback(): """ 如何模拟调用此函数 用 postman 将数据放入 post数据中 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_7&index=8 小程序回调返回的数据 xml格式 :return: """ result_data = {'return_code': 'SUCCESS', 'return_msg': 'OK'} header = {'Content-Type': 'application/xml'} config_mina = app.config['MINA_APP'] target_wechat = WeChatService(merchant_key=config_mina['paykey']) callback_data = target_wechat.xml_to_dict( request.data) # request.data 整个post请求的所有数据 app.logger.info(callback_data) sign = callback_data['sign'] callback_data.pop('sign') # 检测这个签名是否和对应的一样 gene_sign = target_wechat.create_sign(callback_data) app.logger.info(gene_sign) if sign != gene_sign: result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header if callback_data['result_code'] != 'SUCCESS': result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header order_sn = callback_data['out_trade_no'] pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() if not pay_order_info: result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header if int(pay_order_info.total_price * 100) != int( callback_data['total_fee']): result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header if pay_order_info.status == 1: return target_wechat.dict_to_xml(result_data), header target_pay = PayService() # 处理parorder 更新状态值 target_pay.orderSuccess(pay_order_id=pay_order_info.id, params={"pay_sn": callback_data['transaction_id']}) # 回调结果放入记录表里 target_pay.addPayCallbackData(pay_order_id=pay_order_info.id, data=request.data) return target_wechat.dict_to_xml(result_data), header
def orderPay(): resp = {'code': 200, 'msg': '操作成功~', 'data': {}} member_info = g.member_info req = request.values order_sn = req['order_sn'] if 'order_sn' in req else '' pay_order_info = PayOrder.query.filter_by(order_sn=order_sn, member_id=member_info.id).first() if not pay_order_info: resp['code'] = -1 resp['msg'] = "系统繁忙。请稍后再试~~" return jsonify(resp) oauth_bind_info = OauthMemberBind.query.filter_by(member_id=member_info.id).first() if not oauth_bind_info: resp['code'] = -1 resp['msg'] = "系统繁忙。请稍后再试~~" return jsonify(resp) config_mina = app.config['MINA_APP'] # 回调地址 notify_url = app.config['APP']['domain'] + config_mina['callback_url'] target_wechat = WeChatService(merchant_key=config_mina['paykey']) data = { 'appid': config_mina['appid'], 'mch_id': config_mina['mch_id'], 'nonce_str': target_wechat.get_nonce_str(), 'body': '订餐', # 商品描述 'out_trade_no': pay_order_info.order_sn, # 商户订单号 'total_fee': int(pay_order_info.total_price * 100), 'notify_url': notify_url, 'trade_type': "JSAPI", 'openid': oauth_bind_info.openid } pay_info = target_wechat.get_pay_info(pay_data=data) # 保存prepay_id为了后面发模板消息 # pay_order_info.prepay_id = pay_info['prepay_id'] pay_order_info.prepay_id = '1234567' db.session.add(pay_order_info) db.session.commit() resp['data']['pay_info'] = pay_info return jsonify(resp)
def callBack(): # 返回给微信使用 result_data = { 'return_code':'SUCCESS', 'return_msg':'OK' } header = {'content-Type':'application/xml'} # 对微信下单成功后的返回给我们的信息(xml)进行验证 config_mina = app.config['MINA_APP'] target_wechat = WeChatService(merchant_key=config_mina['paykey']) # 取出微信给我们的xml信息,并转换成dict数据格式 callback_data = target_wechat.xml_to_dict(request.data) app.logger.info(callback_data) # 取出sign值(签名),再生成一次sign值,做比较,防止伪造 ****************************** sign = callback_data['sign'] callback_data.pop('sign') gene_sign = target_wechat.create_sign(callback_data) app.logger.info(gene_sign) # 两次sign值做比较,如果测试官网的回调函数代码,这个步骤就要省略 # if sign != gene_sign: # result_data['return_code'] = result_data['return_msg'] = 'FAIL' # return target_wechat.dict_to_xml(result_data),header # 对比金钱的数量是否正确 **************************** # 取出订单号查询对应的订单信息 order_sn = callback_data['out_trade_no'] pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() app.logger.info('牛逼',pay_order_info) if not pay_order_info: result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header if int(pay_order_info.total_price * 100) != int(callback_data['total_fee']): result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header # 微信会有间隔的返回数据,如果订单的状态已经置为1,则直接返回 if pay_order_info.status == 1: return target_wechat.dict_to_xml(result_data), header # 下单成功(微信支付回调成功的操作:pay_order的状态置为1,其他状态值也要修改) target_pay = PayService() target_pay.orderSuccess(pay_order_id=pay_order_info.id,params={'pay_sn':callback_data['transaction_id']}) # 将微信回调的信息存表 target_pay.addPayCallbackData(pay_order_id=pay_order_info.id,data=request.data) return target_wechat.dict_to_xml(result_data),header
def orderPay(): resp = {"code": 200, "msg": "操作成功~", "data": {}} req = request.values member_info = g.member_info order_sn = req["order_sn"] if "order_sn" in req else "" pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() if not pay_order_info: resp["code"] = -1 resp["msg"] = "系统繁忙,请稍后重试!" return jsonify(resp) oauth_bind_info = OauthMemberBind.query.filter_by( member_id=member_info.id).first() if not oauth_bind_info: resp["code"] = -1 resp["msg"] = "系统繁忙,请稍后重试!" return jsonify(resp) config_mina = app.config["MINA_APP"] notify_url = app.config["APP"]["domain"] + config_mina["callback_url"] target_wechat = WeChatService(merchant_key=config_mina["paykey"]) data = { "appid": config_mina["appid"], "mch_id": config_mina["mch_id"], "nonce_str": target_wechat.get_nonce_str(), "body": "订餐", "out_trade_no": pay_order_info.order_sn, "total_price": int(pay_order_info.total_price * 100), "notify_url": notify_url, "trade_type": "JSAPI", "openid": oauth_bind_info.openid } pay_info = target_wechat.get_pay_info(data) # 保存 prepay_id 为了后面发模板消息 pay_order_info.prepay_id = pay_info["prepay_id"] db.session.add(pay_order_info) db.session.commit() resp["data"]["pay_info"] = pay_info return jsonify(resp)
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)) #当月数量 # query( 0, 1) 当中指针为0 和 1的两个对象。 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() app.logger.info("当月数量:tmp_stat_info:" + tmp_stat_info) 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() keyword1_val = pay_order_info.note if pay_order_info.note else '无' keyword2_val = "、".join(notice_content) keyword3_val = str(pay_order_info.total_price) keyword4_val = str(pay_order_info.order_number) keyword5_val = "" if pay_order_info.express_info: express_info = json.loads(pay_order_info.express_info) keyword5_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/wxopen/template/send?access_token=%s" % access_token params = { "touser": oauth_bind_info.openid, "template_id": "8aqlWFAjZZ_NnR0_vOvHGcwHglvIlAYRaUyOmFD5kvs", "page": "pages/my/order_list", "form_id": pay_order_info.prepay_id, "data": { "keyword1": { "value": keyword1_val }, "keyword2": { "value": keyword2_val }, "keyword3": { "value": keyword3_val }, "keyword4": { "value": keyword4_val }, "keyword5": { "value": keyword5_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
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.fitter_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() keyword1_val = pay_order_info.note if pay_order_info.note else "无" keyword2_val = "、".join(notice_content) keyword3_val = str(pay_order_info.total_price) keyword4_val = str(pay_order_info.order_number) keyword5_val = "" target_wechat = WeChatService() access_token = target_wechat.getAccessToken() headers = {"Content-Type": "application/json"} url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s" % access_token params = { "touser": oauth_bind_info.openid, "template_id": "7_a2OIu9QJ5dkYjA6HIU5i7FOFKM9nqpgoWCw0qmaqA", "page": "pages/my/order_list", "form_id": pay_order_info.prepay_id, "data": { "keyword1": { "value": keyword1_val }, "keyword2": { "value": keyword2_val }, "keyword3": { "value": keyword3_val }, "keyword4": { "value": keyword4_val }, "keyword5": { "value": keyword5_val } } } r = requests.post(url=url, data=json.dumps(params), headers=headers) r.encoding = "utf-8" app.logger.info(r.text) return True
def handlePay(self, item): data = json.loads(item.data) if 'member_id' not in data or 'pay_order_id' not in data: return False # 查询用户的openid用于post发送数据 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() app.logger.info(pay_order_info.prepay_id) # 商品信息 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 = 0 # db.session.add(tmp_food_info) # db.session.commit() # 拼接模板消息 keyword1_val = pay_order_info.note if pay_order_info.note else '无' keyword2_val = ','.join(notice_content) keyword3_val = str(pay_order_info.total_price) keyword4_val = str(pay_order_info.pay_time) keyword5_val = "" # 快递信息 # 首先拿出对应token_access 用于发送post请求 target_wechat = WeChatService() access_token = target_wechat.getAccessToken() url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s' % ( access_token) headers = {'Content-Type': 'application/json'} params = { "touser": oauth_bind_info.openid, "template_id": "0TYMLGfoxWFHK7UMc3p0pOVVrbtwEDGjnm5ewQ8uZKc", # 页面跳转到订单页 "page": "pages/my/order_list", "form_id": str(pay_order_info.prepay_id), "data": { "keyword1": { "value": keyword1_val }, "keyword2": { "value": keyword2_val }, "keyword3": { "value": keyword3_val }, "keyword4": { "value": keyword4_val }, "keyword5": { "value": keyword5_val }, }, } r = requests.post(url=url, data=json.dumps(params), headers=headers) r.encoding = 'utf-8' # image_data = target_wechat.getImage() app.logger.info(r.text) return True
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 = tmp_month_count db.session.add(tmp_food_info) db.session.commit() # 模板消息,需要再微信那里设置下好像 keyword1_val = pay_order_info.note if pay_order_info.note else '无' keyword2_val = "、".join(notice_content) keyword3_val = str(pay_order_info.total_price) keyword4_val = str(pay_order_info.order_number) keyword5_val = "" # adress target_wechat = WeChatService() access_token = target_wechat.getAccessToken() headers = {'Content-Type': 'application/json'} url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s" % access_token params = { "touser": oauth_bind_info.openid, "template_id": "i2G8GwCDQ3h5oXGuhXzOERA1b8wLjwNZtwK2aXB9l7E", # 自己模板里边的id "page": "pages/my/order_list", "form_id": pay_order_info.prepay_id, "data": { "keyword1": { "value": keyword1_val }, "keyword2": { "value": keyword2_val }, "keyword3": { "value": keyword3_val }, "keyword4": { "value": keyword4_val }, "keyword5": { "value": keyword5_val } } } r = requests.post(url=url, data=json.dumps(params), headers=headers) r.encoding = "urf8" app.logger.info(r.text) return True
def orderCallback(): """ <xml> <appid><![CDATA[wx2421b1c4370ec43b]]></appid> <attach><![CDATA[支付测试]]></attach> <bank_type><![CDATA[CFT]]></bank_type> <fee_type><![CDATA[CNY]]></fee_type> <is_subscribe><![CDATA[Y]]></is_subscribe> <mch_id><![CDATA[10000100]]></mch_id> <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str> <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid> <out_trade_no><![CDATA[1409811653]]></out_trade_no> <result_code><![CDATA[SUCCESS]]></result_code> <return_code><![CDATA[SUCCESS]]></return_code> <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign> <time_end><![CDATA[20140903131540]]></time_end> <total_fee>1</total_fee> <coupon_fee><![CDATA[10]]></coupon_fee> <coupon_count><![CDATA[1]]></coupon_count> <coupon_type><![CDATA[CASH]]></coupon_type> <coupon_id><![CDATA[10000]]></coupon_id> <coupon_fee><![CDATA[100]]></coupon_fee> <trade_type><![CDATA[JSAPI]]></trade_type> <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id> </xml> """ result_data = {'return_code': 'SUCCESS', 'return_msg': 'OK'} header = {'Content-Type': 'application/xml'} config_mina = app.config['MINA_APP'] target_wechat = WeChatService(merchant_key=config_mina['paykey']) callback_data = target_wechat.xml_to_dict(request.data) app.logger.info(callback_data) sign = callback_data['sign'] callback_data.pop('sign') gene_sign = target_wechat.create_sign(callback_data) app.logger.info(gene_sign) if sign != gene_sign: result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header if callback_data['result_code'] != 'SUCCESS': result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header order_sn = callback_data['out_trade_no'] pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first() if not pay_order_info: result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header if int(pay_order_info.total_price * 100) != int( callback_data['total_fee']): result_data['return_code'] = result_data['return_msg'] = 'FAIL' return target_wechat.dict_to_xml(result_data), header if pay_order_info.status == 1: return target_wechat.dict_to_xml(result_data), header target_pay = PayService() target_pay.orderSuccess(pay_order_id=pay_order_info.id, params={"pay_sn": callback_data['transaction_id']}) # 将微信回调的结果放入记录表 target_pay.addPayCallbackData(pay_order_id=pay_order_info.id, data=request.data) return target_wechat.dict_to_xml(result_data), header
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 # update total sales pay_order_items = PayOrderItem.query.filter_by(pay_order_id=pay_order_info.id).all() notice_content = [] if pay_order_items: # the start time of this month date_from = datetime.datetime.now().strftime("%Y-%m-01 00:00:00") # the end time of this month date_to = datetime.datetime.now().strftime("%Y-%m-31 23:59:59") for item in pay_order_items: tmp_quant_info = Quant.query.filter_by(id=item.quant_id).first() if not tmp_quant_info: continue notice_content.append("%s %s个" % (tmp_quant_info.name, item.quantity)) # 当月数量 tmp_stat_info = db.session.query(QuantSaleChangeLog, func.sum(QuantSaleChangeLog.quantity).label("total")) \ .filter(QuantSaleChangeLog.quant_id == item.quant_id) \ .filter(QuantSaleChangeLog.created_time >= date_from, QuantSaleChangeLog.created_time <= date_to).first() tmp_month_count = tmp_stat_info[1] if tmp_stat_info[1] else 0 tmp_quant_info.total_count += 1 tmp_quant_info.month_count = tmp_month_count db.session.add(tmp_quant_info) db.session.commit() keyword1_val = pay_order_info.note if pay_order_info.note else '没有' keyword2_val = "、".join(notice_content) keyword3_val = str(pay_order_info.total_price) keyword4_val = str(pay_order_info.order_number) keyword5_val = "" if pay_order_info.express_info: express_info = json.loads(pay_order_info.express_info) keyword5_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/wxopen/template/send?access_token=%s" % access_token params = { "touser": oauth_bind_info.openid, "template_id": "x3WlkSg_EAnH6N6IzggoN1HHjvbLPGTk1yBUXhPfsDA", "page": "pages/my/order_list", "form_id": pay_order_info.prepay_id, "data": { "keyword1": { "value": keyword1_val }, "keyword2": { "value": keyword2_val }, "keyword3": { "value": keyword3_val }, "keyword4": { "value": keyword4_val }, "keyword5": { "value": keyword5_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
def handlePay(self, item): ''' 发送模板消息 :param item: :return: ''' data = json.loads(item.data) if 'member_id' not in data or 'pay_order_id' not in data: return False pay_order_info = PayOrder.query.filter_by( id=data['pay_order_id']).first() if not pay_order_info: return False # 查询是否需要是否是绑定用户 需要openid 发送模板 oauth_bind_info = OauthMemberBind.query.filter_by( member_id=data['member_id']).first() if not oauth_bind_info: return False # 拼接模板需要的信息 pay_order_item = PayOrderItem.query.filter_by( pay_order_id=pay_order_info.id).all() notice_content = [] # 更新销售数量 food 表总的销售数量 和月销售数量 if pay_order_item: 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_item: 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_stat_info[1] 是 FoodSaleChangeLog tmp_stat_info[1] 是 func.sum(FoodSaleChangeLog.quantity) 'total' 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() keyword1_val = pay_order_info.note if pay_order_info.note else '无' keyword2_val = "、".join(notice_content) keyword3_val = str(pay_order_info.total_price) keyword4_val = str(pay_order_info.order_number) keyword5_val = "北京市" # 获取access_token target_wechat = WeChatService() access_token = target_wechat.get_access_token() headers = {'Content-Type': 'application/json'} url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s" % access_token params = { "touser": oauth_bind_info.openid, "template_id": "WKdxNY93tMi19cLClxp2AK7FIlD_Ma9cQvWC3ODUPdo", "page": "pages/my/order_list", "form_id": pay_order_info.prepay_id, "data": { "keyword1": { "value": keyword1_val }, "keyword2": { "value": keyword2_val }, "keyword3": { "value": keyword3_val }, "keyword4": { "value": keyword4_val }, "keyword5": { "value": keyword5_val } } } print('...---------------------') r = requests.post(url=url, data=json.dumps(params), headers=headers) r.encoding = "utf-8" app.logger.info(r.text) return True
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
def handlePay(self, item): data = json.loads(item) 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_book_info = Book.query.filter_by(id=item.book_id).first() if not tmp_book_info: continue notice_content.append("《%s》 %s份" % (tmp_book_info.name, item.quantity)) # 当月的销量 tmp_stat_info = db.session.query(BookSaleChangeLog, func.sum(BookSaleChangeLog.quantity).label('total'))\ .filter(BookSaleChangeLog.book_id == item.book_id)\ .filter(BookSaleChangeLog.created_time >= date_from, BookSaleChangeLog.created_time <= date_to).first() tmp_month_count = tmp_stat_info[1] if tmp_stat_info[1] else 0 tmp_book_info.total_count += 1 tmp_book_info.month_count = 0 db.session.add(tmp_book_info) db.session.commit() keyword1_val = "、".join(notice_content) keyword2_val = str(pay_order_info.total_price) keyword3_val = str(pay_order_info.order_number) keyword4_val = "" # todo target_wechat = WeChatService() access_token = target_wechat.getAccessToken() headers = {'Content-Type': 'application/xml'} url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s" % access_token params = { "touser": oauth_bind_info.openid, "template_id": "j4XkDmbp6uXuho20Z63xBElSW9gupExdq44cbKGUoIc", "page": "pages/my/order_list", "form_id": pay_order_info.prepay_id, "data": { "keyword1": { "value": keyword1_val }, "keyword2": { "value": keyword2_val }, "keyword3": { "value": keyword3_val }, "keyword4": { "value": keyword4_val } } } r = requests.post(url=url, data=json.dumps(params), headers=headers) r.encoding = "utf-8" app.logger.info(r.text) return True
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_food_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() keyword1_val = pay_order_info.note if pay_order_info.note else '无' keyword2_val = "、".join(notice_content) keyword3_val = str(pay_order_info.total_price) keyword4_val = str(pay_order_info.order_number) keyword5_val = "" # 快递信息 target_wechat = WeChatService() access_token = target_wechat.getAccessToken() # 网址https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html # https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN 订阅 # https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN 模板 url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s" % access_token params = { "touser": oauth_bind_info.openid, "template_id": "TEMPLATE_ID", "page": "pages/my/order_list", "miniprogram_state": "developer", "lang": "zh_CN", "data": { "keyword1": { "value": keyword1_val }, "keyword2": { "value": keyword2_val }, "keyword3": { "value": keyword3_val }, "keyword4": { "value": keyword4_val }, "keyword5": { "value": keyword5_val } } } headers = {'Content-Type': 'application/json'} r = requests.post(url=url, data=json.dumps(params), headers=headers) r.encoding = 'utf-8' app.logger.info(r.text) return True