def _init_wx_pay(self, trade_type="APP"): if trade_type == "JSAPI": wxpay = WeChatPay(appid=settings.WEIXIN_PUBLIC["app_id"], api_key=settings.WX_PAY_API_KEY, mch_id=settings.WX_PAY_MCH_ID, mch_cert=settings.WX_PAY_MCH_CERT_PATH, mch_key=settings.WX_PAY_MCH_KEY_PATH) else: wxpay = WeChatPay(appid=settings.WX_PAY_APP_ID, api_key=settings.WX_PAY_API_KEY, mch_id=settings.WX_PAY_MCH_ID, mch_cert=settings.WX_PAY_MCH_CERT_PATH, mch_key=settings.WX_PAY_MCH_KEY_PATH) return WxPayment(wxpay, trade_type)
def get_wechat_pay_object(self): sandbox = self.get_param("wechat.sandbox", "0") != "0" if sandbox: _logger.info("Sandbox Mode is used for WeChat API") _logger.debug( "WeChat Credentials: app_id=%s, app_secret=%s, mch_id=%s, sub_mch_id=%s, sandbox mode is %s, cert=%s, key=%s", self.get_param("wechat.app_id", ""), "%s..." % self.get_param("wechat.app_secret", "")[:5], self.get_param("wechat.mch_id", ""), self.get_param("wechat.sub_mch_id", ""), sandbox, self.get_param("wechat.mch_cert", ""), self.get_param("wechat.mch_key", ""), ) return WeChatPay( self.get_param("wechat.app_id", ""), self.get_param("wechat.app_secret", ""), self.get_param("wechat.mch_id", ""), sub_mch_id=self.get_param("wechat.sub_mch_id", ""), sandbox=sandbox, mch_cert=self.get_param("wechat.mch_cert", ""), mch_key=self.get_param("wechat.mch_key", ""), # TODO addd timeout? )
def get_wechat_pay_object(self): sandbox = self.get_param('wechat.sandbox', '0') != '0' if sandbox: _logger.info('Sandbox Mode is used for WeChat API') _logger.debug( 'WeChat Credentials: app_id=%s, app_secret=%s, mch_id=%s, sub_mch_id=%s, sandbox mode is %s, cert=%s, key=%s', self.get_param('wechat.app_id', ''), '%s...' % self.get_param('wechat.app_secret', '')[:5], self.get_param('wechat.mch_id', ''), self.get_param('wechat.sub_mch_id', ''), sandbox, self.get_param('wechat.mch_cert', ''), self.get_param('wechat.mch_key', ''), ) return WeChatPay( self.get_param('wechat.app_id', ''), self.get_param('wechat.app_secret', ''), self.get_param('wechat.mch_id', ''), sub_mch_id=self.get_param('wechat.sub_mch_id', ''), sandbox=sandbox, mch_cert=self.get_param('wechat.mch_cert', ''), mch_key=self.get_param('wechat.mch_key', ''), # TODO addd timeout? )
class Pay(Resource): wechat_pay = WeChatPay(appid=config.app_id, api_key=config.api_key, mch_id=config.mch_id, mch_cert=config.mch_cert, mch_key=config.mch_key) wechat_order = wechat_pay.order wechat_jsapi = wechat_pay.jsapi @ns.doc(decription="支付") @ns.expect(pay_parser) def post(self): try: total_fee = 1 open_id = userBl.get_open_id(code='', username=JwtUtil.get_token_username(flask.request.headers.get("token"))) print(open_id) order_params = self.wechat_order.create(trade_type="JSAPI", body=config.body, total_fee=total_fee, notify_url=config.notify_url, client_ip=config.server_ip, user_id=open_id, device_info="WEB") prepay_id = order_params["prepay_id"] pay_params = self.wechat_jsapi.get_jsapi_params(prepay_id) pay_signature = self.wechat_jsapi.get_jsapi_signature(prepay_id, timestamp=pay_params["timeStamp"], nonce_str=pay_params["nonceStr"]) pay_params["signature"] = pay_signature return pay_params, 200 except PasswordWrongException: return {'error': 'wrong password'}, 403 except NotFoundException: return {'error': 'user not found'}, 404
def setUp(self): self.client = WeChatPay( appid='abc1234', api_key='test123', mch_id='1192221', mch_cert='', mch_key='', )
def setUp(self): self.client = WeChatPay( appid="abc1234", api_key="test123", mch_id="1192221", mch_cert="", mch_key="", )
def wechatpay(): wechat_config = { "appid": "wx2bc82adb627f16fc", "api_key": "yxrs101227SevenStarWeChatpayment", "mch_id": "1394986202", "mch_cert": "file/wechat/apiclient_cert.pem", "mch_key": "file/wechat/apiclient_key.pem", } return WeChatPay(**wechat_config)
def Create_wechatpay_order(): wechatpay = WeChatPay( appid="123456", api_key='fafafafdsffsdafxzcsadsadqd', mch_id='3214324343', mch_cert=os.getcwd() + "/pay/conf/apiclient_cert.pem", mch_key=os.getcwd() + "/pay/conf/apiclient_key.pem", ) return wechatpay
def WeixinPay(): """ 创建微信支付对象 :return: """ # wxPay = WeChatPay(appid=settings.WECHAT_APPID, api_key=settings.MCH_KEY, mch_id=settings.MCH_ID) wxPay = WeChatPay(appid=settings.WECHAT_APPID, api_key=settings.MCH_KEY, mch_id=settings.MCH_ID, mch_cert=settings.API_CLIENT_CERT_PATH, mch_key=settings.API_CLIENT_KEY_PATH) return wxPay
def wxpay(request, order_id): appid = 'wx789c583bc751f9af' # 小程序ID Mch_key = '00000000000000000000000000000000' Mch_id = '1514858131' openid = request.GET.get('open_id') Total = int(Order.objects.get(OrderId=order_id).Total * 100) pay = WeChatPay(appid, Mch_key, Mch_id) order = pay.order.create( trade_type='JSAPI', # 交易类型,小程序取值:JSAPI body='小食记', # 商品描述,商品简单描述 total_fee=Total, # 标价金额,订单总金额,单位为分 notify_url= 'https://www.qqmxd.com/login/payn/', # 通知地址,异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。 user_id=openid # 用户标识,trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。 ) wxpay_params = pay.jsapi.get_jsapi_params(order['prepay_id']) return HttpResponse(json.dumps(wxpay_params))
def get_weixinpay_url(self, obj): openid = self.context['request'].user.openid #code = "0214ENwq1cfd7m0jMrvq1lh7xq14ENwc" #user_info = get_user_info(code) #print(user_info) #openid = user_info['openid'] pay = WeChatPay(WECHAT['APPID'], WECHAT['MERCHANT_KEY'], WECHAT['MCH_ID']) order = pay.order.create( trade_type=WECHAT['TRADE_TYPE'], # 交易类型,小程序取值:JSAPI body=obj.order_sn, # 商品描述,商品简单描述 total_fee=obj.order_mount, # 标价金额,订单总金额,单位为分 out_trade_no=obj.order_sn, notify_url=WECHAT[ 'NOTIFY_URL'], # 通知地址,异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。 user_id=openid # 用户标识,trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。 ) wxpay_params = pay.jsapi.get_jsapi_params(order['prepay_id']) return wxpay_params
def post(self, request): result = ResultResponse(code.ARIES_200_SUCCESS, 'success') request_data = request.data logger_info.info(request_data) # Payment registration and validation check try: payment_type = request_data['payment_type'] order_id = request_data['order_id'] except Exception as e: logger_info.info(str(e)) result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data invalid') return Response(result.get_response(), result.get_code()) # Check if the payment exists payment_count = Payment.objects.filter(order_id=order_id).count() if payment_count != 0: payment = Payment.objects.get(order_id=order_id) if payment.payment_status == 0 or payment.payment_status == 1: result = ResultResponse(code.ARIES_200_SUCCESS, 'success') return Response(result.get_response(), result.get_code()) # Get raw data for validation raw_data = {} # Wechat app payment request_data['payment_raw_data'] = json.dumps(raw_data) try: wechat_serializer = WechatPaymentSerializer(data=request_data) if wechat_serializer.is_valid(): wechat_serializer.save() else: logger_info.info(wechat_serializer.errors) except Exception as e: print(e) logger_info.info(str(e)) if payment_type == 1: wechat_app_id = 'viastelle' merchant_id = 'viastelle' api_key = 'viastelle' nonce_str = payment_util.wechat_payment_str(order_id) else: wechat_app_id = 'viastelle' merchant_id = 'viastelle' api_key = 'viastelle' nonce_str = payment_util.wechat_payment_str(order_id) wechat_client = WeChatPay(wechat_app_id, api_key, merchant_id, sub_mch_id=None, mch_cert=None, mch_key=None) try: query_data = { 'appid': wechat_app_id, 'mch_id': merchant_id, 'out_trade_no': order_id, 'nonce_str': nonce_str } prepaid_signature = utils.calculate_signature(query_data, api_key) query_data_signed = utils.dict_to_xml(query_data, prepaid_signature) url = get_wechat_query_url() headers = {'Content-Type': 'application/xml'} response = requests.post(url, headers=headers, data=query_data_signed) logger_info.info(response.text) response_data = response.content query_result = xmltodict.parse(response_data)['xml'] query_result['order_id'] = order_id request_data['transaction_id'] = query_result['transaction_id'] query_serializer = WechatQuerySerializer(data=query_result) if query_serializer.is_valid(): query_serializer.save() query_data = query_serializer.data else: logger_info.info(query_serializer.errors) # Error case - refund request except Exception as e: logger_info.info(str(e)) result = ResultResponse( code.ARIES_500_INTERNAL_SERVER_ERROR, get_msg(code.ERROR_4005_PAYMENT_SYNC_ERROR)) result.set_error(code.ERROR_4005_PAYMENT_SYNC_ERROR) return Response(result.get_response(), result.get_code()) # Set payment status request_data['payment_status'] = self.PAYMENT_CREATED payment_serializer = PaymentSerializer(data=request_data) # Payment object save if payment_serializer.is_valid(): payment_serializer.save() payment = Payment.objects.get(order_id=order_id) else: logger_info.info(payment_serializer.errors) result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data invalid') return Response(result.get_response(), result.get_code()) # Verification payment if payment_type == self.WECHAT_APP_PAYMENT or payment_type == self.WECHAT_MOBILE_PAYMENT: if query_data['return_code'] == 'SUCCESS' and query_data[ 'result_code'] == 'SUCCESS': # Payment success and check price # if query_data['total_fee'] == int(price_total): del query_result['order_id'] if not wechat_client.check_signature(query_result): payment.payment_status = 4 else: payment.payment_status = 1 payment.save() else: payment.payment_status = 4 payment.save() logger_error.error(code.ERROR_4001_PAYMENT_VALIDATION_FAILED) result = ResultResponse( code.ARIES_500_INTERNAL_SERVER_ERROR, get_msg(code.ERROR_4001_PAYMENT_VALIDATION_FAILED)) result.set_error(code.ERROR_4001_PAYMENT_VALIDATION_FAILED) return Response(result.get_response(), result.get_code()) else: result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data invalid') return Response(result.get_response(), result.get_code()) return Response(result.get_response(), result.get_code())
from wechatpy.utils import check_signature from weshop.utils import ezlogger from configs.config import Config from . import wechat from .chatbot import bot_reply logger = ezlogger.get_logger('wechat', use_stream=False) wechat_client = WeChatClient(Config.WECHAT_APP_ID, Config.WECHAT_APP_SECRET) wechat_oauth = WeChatOAuth(app_id=Config.WECHAT_APP_ID, secret=Config.WECHAT_APP_SECRET, scope='snsapi_userinfo', redirect_uri='') wechat_pay = WeChatPay(appid=Config.WECHAT_APP_ID, api_key=Config.WEPAY_API_KEY, mch_id=Config.WEPAY_MCH_ID, mch_cert=Config.WEPAY_MCH_CERT_PATH, mch_key=Config.WEPAY_MCH_KEY_PATH) wechat_client.menu.create({ "button": [{ "type": "view", "name": "快速订水", "url": "http://www.rockbot.top/weshop/quickbuy" }, { "type": "view", "name": "水站商城", "url": "http://www.qq.com" }] })
:param api_key: 商户 key :param mch_id: 商户号 :param sub_mch_id: 可选,子商户号,受理模式下必填 :param mch_cert: 必填,商户证书路径 :param mch_key: 必填,商户证书私钥路径 :param timeout: 可选,请求超时时间,单位秒,默认无超时设置 :param sandbox: 可选,是否使用测试环境,默认为 False """ wechat_config = { "appid":"wx174d12341715ffef", "api_key":"haipainongchangweixinzhifu123456", "mch_id":"1495392782", # "mch_cert":"file/wechat/apiclient_cert.pem", # "mch_key":"file/wechat/apiclient_key.pem", } wechat_pay = WeChatPay(**wechat_config) """ 统一下单接口 :param trade_type: 交易类型,取值如下:JSAPI,NATIVE,APP,WAP, MWEB :param body: 商品描述 :param total_fee: 总金额,单位分 :param notify_url: 接收微信支付异步通知回调地址 :param client_ip: 可选,APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP :param user_id: 可选,用户在商户appid下的唯一标识。trade_type=JSAPI,此参数必传 :param out_trade_no: 可选,商户订单号,默认自动生成 :param detail: 可选,商品详情 :param attach: 可选,附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据 :param fee_type: 可选,符合ISO 4217标准的三位字母代码,默认人民币:CNY :param time_start: 可选,订单生成时间,默认为当前时间 :param time_expire: 可选,订单失效时间,默认为订单生成时间后两小时
def __init__(self, appid, api_key, mch_id, sub_mch_id=None, mch_cert=None, mch_key=None): self.wx_pay_client = WeChatPay(appid, api_key, mch_id, sub_mch_id, mch_cert, mch_key)