[DEMO] 支付宝网页支付及微信网页扫码支付

合集下载

如何在电商平台上选择合适的支付方式

如何在电商平台上选择合适的支付方式

如何在电商平台上选择合适的支付方式如何选择适合的支付方式在电商平台上选择合适的支付方式是进行网上交易时必须考虑的问题之一。

随着电商的兴起和发展,越来越多的人选择在网上购物,而选择适合的支付方式能够确保交易安全、方便快捷。

本文将介绍一些常见的支付方式,并提供一些建议,以帮助消费者在电商平台上选择合适的支付方式。

1. 支付宝(Alipay)支付宝是中国目前最受欢迎的第三方支付平台之一。

它提供了安全可靠的支付服务,并与众多电商平台合作,方便用户进行在线交易。

支付宝支持多种支付方式,包括余额支付、银行卡支付、信用卡支付等。

用户可以根据自己的需求选择合适的支付方式进行付款。

2. 微信支付(WeChat Pay)微信支付是腾讯旗下的支付平台,与微信的普及程度相辅相成,成为了中国电商支付的重要方式之一。

用户只需要绑定银行卡或信用卡,就可以使用微信支付完成购物支付。

此外,微信支付还提供了方便的扫码支付功能,用户只需扫描商家提供的二维码,即可完成支付。

3. 银联在线支付银联在线支付是由中国银联推出的一种支付服务,用户可以使用银联卡在电商平台上完成支付。

这种支付方式广泛接受,安全可靠。

用户只需输入银联卡号、姓名、CVN验证码等信息,就可以完成交易。

4. PayPalPayPal是一家国际知名的支付平台,用户可以通过PayPal账户完成支付。

PayPal支持全球多种货币的交易,适用于跨国交易。

用户可以绑定银行卡或信用卡到PayPal账户,完成支付时只需输入PayPal账户和密码即可。

在选择支付方式时,消费者应该综合考虑以下几个因素:1. 安全性:选择支付方式时,确保支付平台具有安全可靠的支付系统,保护个人信息和资金安全。

2. 方便性:选择支付方式时,考虑是否方便快捷,操作简单。

例如,绑定银行卡或信用卡的支付方式,可以在不离开网页的情况下完成付款。

3. 适应性:选择支付方式时,考虑支付平台是否支持多种货币,以适应不同国家和地区的交易需求。

完全指南:网络支付的使用教程(二)

完全指南:网络支付的使用教程(二)

完全指南:网络支付的使用教程随着科技的飞速发展和人们对便利性的追求,网络支付已经成为了我们日常生活中不可或缺的一部分。

不管是在网上购物,还是在餐厅付账,网络支付都提供了快捷、安全的支付方式。

本文将为您提供一个完全指南,帮助您更好地利用网络支付。

一、网络支付的介绍互联网支付,顾名思义,就是通过互联网进行支付的一种方式。

它可以通过网上银行、支付宝、微信支付等多种平台实现。

相比传统的线下支付方式,网络支付不仅速度更快,还能够实现跨境支付,方便跨国交易。

二、首次使用网络支付的步骤1. 注册账号:在选择合适的支付平台后,您需要注册一个账号。

通常需要提供基本的个人信息和联系方式,以确保您的支付安全。

2. 绑定银行卡或信用卡:为了方便您的资金存取,您需要将自己的银行卡或信用卡与支付平台进行绑定。

这一步通常需要输入您的银行卡或信用卡信息,并进行身份验证。

3. 设置支付密码:为了确保支付安全,支付平台通常要求您设置一个支付密码。

请确保您的支付密码足够复杂,并定期更换以提高账户安全性。

三、常见的网络支付方式1. 网上银行支付:这是最常见的一种网络支付方式,通过银行的网上支付平台实现支付。

您需要登录网上银行,选择转账或支付功能,并输入相应的信息完成支付。

2. 扫码支付:支付宝和微信支付都提供了扫码支付的功能。

商家会生成一个二维码,您只需要打开支付宝或微信扫描二维码,并确认支付金额即可完成支付。

3. 第三方支付平台:除了支付宝和微信支付外,还有一些其他第三方支付平台如财付通、银联在线等,您可以根据自己的需求选择适合自己的平台进行支付。

四、网络支付的优势与注意事项1. 优势:a. 便捷性:网络支付可以随时随地进行,无需携带现金或银行卡。

b. 安全性:网络支付平台通常采用加密算法,确保您的支付信息不被泄露。

c. 快速性:支付完成后,资金可以即时到账,提高了交易效率。

d. 跨境支付:网络支付可以轻松实现跨境交易,方便国际间的商务合作。

php实现支付宝在线支付和扫码支付demo

php实现支付宝在线支付和扫码支付demo

php实现⽀付宝在线⽀付和扫码⽀付demophp实现⽀付宝在线⽀付和扫码⽀付demo背景:在做⼀个公众号时增加了h5端,需要接⼊⽀付,⾮微信环境,选择了⽀付宝,以下简单记录下实现过程,并做了简单的封装,拿来即可使⽤,注意:本项⽬只是基于官⽅demo修改的,需要接⼊⾃⼰项⽬的需要按需获取到。

demo的github地址:⽬录结构:以下的⽂件⽬录⽆需修改,只修改config.php配置⽂件和paytest.php和create_qrcode.php⽂件/aop //核⼼库/img //⼆维码中⼼的icon(⾃⼰引⼊的)/lib //核⼼库/lotusphp_runtime //没⽤到/phpqrcode //⽣成⼆维码的插件(扫码⽀付时⾃⼰引⼊的,没⽤官⽅的)/service //官⽅demo的测试⽂件(没⽤到)AopSdk.php //demo项⽬⼊⼝⽂件,不⽤修改config.php //重要,存放配置⽂件create_qrcode.php //⼆维码扫码⽀付demonotify_url.php //异步回调地址(只测试了⽀付,没⽤到)paytest.php //在线⽀付demoreturn_url.php //同步跳转地址(没⽤到)步骤:1. 申请⽀付宝开发者2. 创建沙箱应⽤,获取到appId3. 获取公钥秘钥等信息,修改config.php4. 修改⽂件实现⽀付功能在线⽀付代码:paytest.php<?php/*** 功能:⽀付宝⽀付测试⽂件* 版本:v1.0* author:wangkk* 以下部分就是具体的⽀付过程,只需要引⼊⾃⼰的配置⽂件$config数组信息,同时需要获取订单信息即可使⽤*///引⼊sdk⽂件require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'aop/AopClient.php';require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'aop/request/AlipayTradeWapPayRequest.php';//引⼊配置⽂件信息require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'config.php';/*** ⽀付宝⽀付类的封装*/class Alipay{//配置⽂件数据public $alipay_config;//构造函数,获取数据public function __construct($alipay_config){//配置项$this->gateway_url = $alipay_config['gatewayUrl'];$this->appid = $alipay_config['app_id'];$this->private_key = $alipay_config['merchant_private_key'];$this->alipay_public_key = $alipay_config['alipay_public_key'];$this->charset = $alipay_config['charset'];$this->signtype = $alipay_config['sign_type'];$this->notify_url = $alipay_config['notify_url'];$this->return_url = $alipay_config['return_url'];if(empty($this->appid) || trim($this->appid) == ""){throw new Exception("appid不能为空!");}if(empty($this->private_key) || trim($this->private_key) == ""){throw new Exception("商户密钥不能为空!");}if(empty($this->alipay_public_key) || trim($this->alipay_public_key) == ""){throw new Exception("商户公钥不能为空!");}if(empty($this->charset) || trim($this->charset)== "" ){throw new Exception("编码格式不能为空");}if(empty($this->gateway_url) || trim($this->gateway_url) == ""){throw new Exception("⽀付⽹关地址不能为空!");}if(empty($this->notify_url) || trim($this->notify_url) == ""){throw new Exception("异步回调地址不能为空!");}}public function pay(){//订单号,⾃定义,唯⼀$out_trade_no = $_GET['out_trade_no'];/** --------------------------------以下部分需要修改:获取订单信息 start--------------------------------- **/ //通过订单号获取到订单信息// $orderInfo = M('order')->where(['out_trade_no'=>$out_trade_no])->find();// if(empty($orderInfo)){// throw new Exception("查⽆此订单");// }// //参数列表// $body = $orderInfo['body']; //商品描述,可为空// $subject = $orderInfo['subject']; //订单标题,必填// $out_trade_no = $orderInfo['out_trade_no']; //订单号,必填// $total_amount = $orderInfo['total_amount']; //订单⾦额,必填/** --------------------------------以上部分需要修改:获取订单信息 end--------------------------------- **/ //订单测试信息,真实项⽬把以下⼏⾏删除,使⽤上边的真实数据$body = '商品描述'; //商品描述,可为空$subject = '订单标题'; //订单标题,必填$out_trade_no = rand(10000,99999); //订单号,必填$total_amount = rand(1,5); //订单⾦额,必填$timeout_express = '1m'; //超时,1分钟$product_code = 'QUICK_WAP_WAY'; //⼿机端⽀付宝if(empty($subject) || trim($subject) == ""){throw new Exception("订单标题不能为空");}if(empty($total_amount) || trim($total_amount) == ""){throw new Exception("订单⾦额不能为空");}//组装订单数据$bizContentarr = array('body' => $body ? $body : '', //商品描述,可以为空'subject' => $subject,'out_trade_no' => $out_trade_no,'total_amount' => $total_amount,'timeout_express' => $timeout_express,'product_code' => $product_code,);$bizContent = json_encode($bizContentarr,JSON_UNESCAPED_UNICODE);//设置数据$aopObj = new \AopClient();$aopObj->gatewayUrl = $this->gateway_url;$aopObj->appId = $this->appid;$aopObj->rsaPrivateKey = $this->private_key;$aopObj->alipayrsaPublicKey = $this->alipay_public_key;$aopObj->apiVersion = '1.0';$aopObj->postCharset = $this->charset;$aopObj->format = 'json';$aopObj->signType = $this->signtype;//设置请求的数据$request = new \AlipayTradeWapPayRequest ();$request->setBizContent($bizContent);$request->setNotifyUrl($this->notify_url);$request->setReturnUrl($this->return_url);$result = $aopObj->pageExecute($request);echo $result;}}//获取到配置⽂件,框架⾥的话直接放在配置⽂件中,通过框架⽅法去获取$configInfo = $config;$AlipayObj = new Alipay($configInfo);$AlipayObj->pay();扫码⽀付代码:create_qrcode.php<?php/*** 功能:⽀付宝⽣成⼆维码* 版本:v1.0* author:wangkk* 以下部分就是具体的⽣成⼆维码过程,只需要引⼊⾃⼰的配置⽂件$config数组信息,同时需要获取订单信息即可使⽤ *///引⼊sdk⽂件require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'aop/AopClient.php';require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'aop/request/AlipayTradePrecreateRequest.php';//引⼊配置⽂件信息require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'config.php';//引⼊⽣成⼆维码的插件require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'phpqrcode/phpqrcode.php';class CreateQrcode{public function __construct($alipay_config){//配置项$this->gateway_url = $alipay_config['gatewayUrl'];$this->appid = $alipay_config['app_id'];$this->private_key = $alipay_config['merchant_private_key'];$this->alipay_public_key = $alipay_config['alipay_public_key'];$this->charset = $alipay_config['charset'];$this->signtype = $alipay_config['sign_type'];$this->notify_url = $alipay_config['notify_url'];$this->return_url = $alipay_config['return_url'];if(empty($this->appid) || trim($this->appid) == ""){throw new Exception("appid不能为空!");}if(empty($this->private_key) || trim($this->private_key) == ""){throw new Exception("商户密钥不能为空!");}if(empty($this->alipay_public_key) || trim($this->alipay_public_key) == ""){throw new Exception("商户公钥不能为空!");}if(empty($this->charset) || trim($this->charset)== "" ){throw new Exception("编码格式不能为空");}if(empty($this->gateway_url) || trim($this->gateway_url) == ""){throw new Exception("⽀付⽹关地址不能为空!");}if(empty($this->notify_url) || trim($this->notify_url) == ""){throw new Exception("异步回调地址不能为空!");}}//⽀付public function pay(){//订单号,⾃定义,唯⼀$out_trade_no = $_GET['out_trade_no'];/** --------------------------------以下部分需要修改:获取订单信息 start--------------------------------- **///通过订单号获取到订单信息// $orderInfo = M('order')->where(['out_trade_no'=>$out_trade_no])->find();// if(empty($orderInfo)){// throw new Exception("查⽆此订单");// }// //参数列表// $body = $orderInfo['body']; //商品描述,可为空// $subject = $orderInfo['subject']; //订单标题,必填// $out_trade_no = $orderInfo['out_trade_no']; //订单号,必填// $total_amount = $orderInfo['total_amount']; //订单⾦额,必填/** --------------------------------以上部分需要修改:获取订单信息 end--------------------------------- **///订单测试信息,真实项⽬把以下⼏⾏删除,使⽤上边的真实数据$body = '商品描述'; //商品描述,可为空$subject = '订单标题'; //订单标题,必填$out_trade_no = rand(10000,99999); //订单号,必填$total_amount = rand(1,5); //订单⾦额,必填$aopObj = new \AopClient ();//设置值$aopObj->gatewayUrl = $this->gateway_url;$aopObj->appId = $this->appid;$aopObj->rsaPrivateKey = $this->private_key;$aopObj->alipayrsaPublicKey = $this->alipay_public_key;$aopObj->apiVersion = '1.0';$aopObj->postCharset = $this->charset;$aopObj->format = 'json';$aopObj->signType = $this->signtype;$request = new AlipayTradePrecreateRequest();//组装订单数据$timeout_express = '5m'; //超时,1分钟$bizContentarr = array('body' => $body ? $body : '', //商品描述,可以为空'subject' => $subject,'out_trade_no' => $out_trade_no,'total_amount' => $total_amount,'timeout_express' => $timeout_express, //过期时间);$bizContent = json_encode($bizContentarr,JSON_UNESCAPED_UNICODE);$request->setBizContent($bizContent);$result = $aopObj->execute($request);$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";$resultCode = $result->$responseNode->code;if(!empty($resultCode) && $resultCode == 10000){//成功,得到⼆维码,在这不使⽤官⽅的⽅法,官⽅使⽤的是google的,墙内不ok$qr_code_url = $result->$responseNode->qr_code;$icon = './img/logo.png';//准备好的logo图⽚\QRcode::png($qr_code_url,false, 'H', 4, false);$code = ob_get_clean();$code = imagecreatefromstring($code);$logo = imagecreatefrompng($icon);$QR_width = imagesx($code);//⼆维码图⽚宽度$QR_height = imagesy($code);//⼆维码图⽚⾼度$logo_width = imagesx($logo);//logo图⽚宽度$logo_height = imagesy($logo);//logo图⽚⾼度$logo_qr_width = $QR_width / 4;$scale = $logo_width/$logo_qr_width;$logo_qr_height = $logo_height/$scale;$from_width = ($QR_width - $logo_qr_width) / 2;//重新组合图⽚并调整⼤⼩imagecopyresampled($code, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);header ( "Content-type: image/png" );ImagePng($code);echo $qrcode;die;} else {echo 'fail';die;}}}$alipay_config = $config;$CreateQrcodeObj = new CreateQrcode($alipay_config);$CreateQrcodeObj->pay();总结终点就是获取公钥秘钥这部分⼀定不能错,还有就是在真实项⽬中的话按需引⼊sdk⽂件,但aop,lotusphp_runtime这两个⽂件夹是⽀付宝核⼼库,必须引⼊,AopSdk.php是⼊⼝⽂件,必须引⼊。

php实现微信和支付宝支付的示例代码

php实现微信和支付宝支付的示例代码

php实现微信和⽀付宝⽀付的⽰例代码php实现微信⽀付在php下实现微信⽀付,这⾥我使⽤了EasyWeChat这⾥我是在Yii框架实现的,安装EasyWeChat插件composer require jianyan74/yii2-easy-wechat⼀:配置EasyWeChat1:在config/main.php 的 component中添加EasyWeChat的SDK'components' => [// ...'wechat' => ['class' => 'jianyan\easywechat\Wechat','userOptions' => [], // ⽤户⾝份类参数'sessionParam' => 'wechatUser', // 微信⽤户信息将存储在会话在这个密钥'returnUrlParam' => '_wechatReturnUrl', // returnUrl 存储在会话中'rebinds' => [ // ⾃定义服务模块// 'cache' => 'common\components\Cache',]],// ...]2:在config/params.php中设置基础配置信息和微信⽀付信息// 微信配置具体可参考EasyWechat'wechatConfig' => [],// 微信⽀付配置具体可参考EasyWechat'wechatPaymentConfig' => [],// 微信⼩程序配置具体可参考EasyWechat'wechatMiniProgramConfig' => [],// 微信开放平台第三⽅平台配置具体可参考EasyWechat'wechatOpenPlatformConfig' => [],// 微信企业微信配置具体可参考EasyWechat'wechatWorkConfig' => [],// 微信企业微信开放平台具体可参考EasyWechat'wechatOpenWorkConfig' => [],// 微信⼩微商户具体可参考EasyWechat'wechatMicroMerchantConfig' => [],⼆:实现微信⽀付1:微信⽀付api$data = ['body' => '',//⽀付描述'out_trade_no' => '',//订单号'total_fee' => '',//⽀付⾦额'notify_url' => '', // ⽀付结果通知⽹址,如果不设置则会使⽤配置⾥的默认地址'trade_type' => 'JSAPI',//⽀付⽅式'openid' => '',//⽤户openid];// ⽣成⽀付配置$payment = Yii::$app->wechat->payment;$result = $payment->order->unify($data);if ($result['return_code'] == 'SUCCESS') {$prepayId = $result['prepay_id'];$config = $payment->jssdk->sdkConfig($prepayId);} else {throw new yii\base\ErrorException('微信⽀付异常, 请稍后再试');}return $this->render('wxpay', ['jssdk' => $payment->jssdk, // $app通过上⾯的获取实例来获取'config' => $config]);2:在wxpay.php⽂件中发起⽀付<script src="/open/js/jweixin-1.4.0.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8">//数组内为jssdk授权可⽤的⽅法,按需添加,详细查看微信jssdk的⽅法wx.config(<?php echo $jssdk->buildConfig(array('chooseWXPay'), true) ?>);function onBridgeReady(){// 发起⽀付wx.chooseWXPay({timestamp: <?= $config['timestamp'] ?>,nonceStr: '<?= $config['nonceStr'] ?>',package: '<?= $config['package'] ?>',signType: '<?= $config['signType'] ?>',paySign: '<?= $config['paySign'] ?>', // ⽀付签名success: function (res) {// ⽀付成功后的回调函数},cancel: function(r) {//⽀付取消后的回调函数},});}if (typeof WeixinJSBridge == "undefined"){if( document.addEventListener ){document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);}else if (document.attachEvent){document.attachEvent('WeixinJSBridgeReady', onBridgeReady);document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);}}else{onBridgeReady();}</script>在异步回调地址中获取微信⽀付回调只需要使⽤如下⽅法即可:$payment = Yii::$app->wechat->payment;$response = $payment->handlePaidNotify(function($message, $fail) {//⽀付结果逻辑,只有在函数⾥ return true; 才代表处理完成});$response->send();根据如上步骤就可以实现微信⽀付php实现⽀付宝⽀付⼀:在php中安装⽀付宝插件composer require alipaysdk/easysdk⼆:php实现⽀付宝⽀付1:配置⽀付宝/*** ⽀付宝配置*/public static function getOptions(){$options = new Config();$options->protocol = 'https';$options->gatewayHost = '';$options->signType = 'RSA2';$options->appId = '<-- 请填写您的AppId,例如:2019022663440152 -->';// 为避免私钥随源码泄露,推荐从⽂件中读取私钥字符串⽽不是写⼊源码中$options->merchantPrivateKey = '<-- 请填写您的应⽤私钥,例如:MIIEvQIBADANB ... ... -->';$options->alipayCertPath = '<-- 请填写您的⽀付宝公钥证书⽂件路径,例如:/foo/alipayCertPublicKey\_RSA2.crt -->';$options->alipayRootCertPath = '<-- 请填写您的⽀付宝根证书⽂件路径,例如:/foo/alipayRootCert.crt" -->';$options->merchantCertPath = '<-- 请填写您的应⽤公钥证书⽂件路径,例如:/foo/appCertPublicKey\_2019051064521003.crt -->'; //注:如果采⽤⾮证书模式,则⽆需赋值上⾯的三个证书路径,改为赋值如下的⽀付宝公钥字符串即可// $options->alipayPublicKey = '<-- 请填写您的⽀付宝公钥,例如:MIIBIjANBg... -->';//可设置异步通知接收服务地址(可选)$options->notifyUrl = "<-- 请填写您的⽀付类接⼝异步通知接收服务地址,例如:https:///callback -->";//可设置AES密钥,调⽤AES加解密相关接⼝时需要(可选)//$options->encryptKey = "<-- 请填写您的AES密钥,例如:aa4BtZ4tspm2wnXLb1ThQA== -->";return $options;}2:实现⽀付宝⽀付//加载⽀付宝配置Factory::setOptions(self::getOptions());try {//发起API调⽤$result = Factory::payment()->wap()->pay('订单标题', '商户订单号', '订单总⾦额', '⽤户付款中途退出返回商户⽹站的地址', '⽀付回调地址');$responseChecker = new ResponseChecker();//处理响应或异常if ($responseChecker->success($result)) {//调⽤成功return $result->body;} else {//调⽤失败$errorMsg = $result->msg . $result->subMsg;throw new yii\\base\\ErrorException($errorMsg);}} catch (\\Exception $e) {throw new yii\\base\\ErrorException($e->getMessage());}根据如上就可以实现⽀付宝⽀付到此这篇关于php实现微信和⽀付宝⽀付的⽰例代码的⽂章就介绍到这了,更多相关php实现微信和⽀付宝⽀付内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

支付宝和微信支付流程和技术说明

支付宝和微信支付流程和技术说明

支付宝和微信支付流程和技术说明
1.1微信支付
1.1.1JSAPI网页支付
JSAPI网页支付即前文说的公众号支付,可在微信公众号、朋友圈、聊天会话中点击页面链接,或者用微信“扫一扫”扫描页面地址二维码在微
信中打开商户HTML5页面,在页面内下单完成支付。

1.1.2Native原生支付
Native原生支付即前文说的扫码支付,商户根据微信支付协议格式生成的二维码,用户通过微信“扫一扫”扫描二维码后即进入付款确认界面,输入密码即完成支付。

1.1.3接入方式
微信支付系统是指完成微信支付流程中涉及的
API接口、后台业务处理系统、账务系统、回调通知等系统的总称。

微信支付分为公众号支付,App支付,扫码支付(包括PC 网站),刷卡支付(设备扫描用户手
机)
本项目主要适用扫码支付。

接通扫码支付流程:
注册公众帐号申请微信
认证
申请微信
支付
商户平台
进行验证
在线签署
协议
启动设计
和开发
用户扫描商户展示在各种场景的二维码进行支付。

步骤1:商户根据微信支付的规则,为不同商品生成不同的二维码,展示在各种场景,用于用户扫描购买。

步骤2:用户使用微信“扫一扫”扫描二维码后,获取商品支付信息,引导用户完成支付。

步骤(3):用户确认支付,输入支付密码。

步骤(4):支付完成后会提示用户支付成功,商户后台得到支付成功的通知,然后进行发货处理。

开发步骤:。

记录:c#实现微信,支付宝扫码支付(一)

记录:c#实现微信,支付宝扫码支付(一)

记录:c#实现微信,支付宝扫码支付(一)因为公司系统业务需要,这几天了解了一下微信和支付宝扫码支付的接口,并用c#实现了微信和支付宝扫码支付的功能。

微信支付分为6种支付模式:1.付款码支付,2.native支付,3.jsapi支付,4.app支付,5.h5支付,6.小程序支付我在这里用到的是native支付,就是网页生成二维码让用户扫码支付,再调用回调接口判断用户是否支付成功。

支付宝支付api也挺多的,我只使用了一些我在系统中能够用到的,现在将代码简单记录在这里,先从微信支付开始。

微信支付先上后台代码:传入参数(总金额一定要是int类型,微信默认是以分为单位),获取支付的url,然后用二维码生成工具将url地址转换为二维码图片并将文件流传回前台/*** 生成直接支付url,支付url有效期为2小时,模式二* @param productId 商品ID* @return 模式二URL*/public ActionResult GetPayUrl(){//参数WxPayData data = new WxPayData();data.SetValue("body", “test”);//商品描述data.SetValue("attach", "");//附加数据data.SetValue("out_trade_no",WxPayApi.GenerateOutTradeNo());//随机字符串data.SetValue("total_fee", 100);//总金额data.SetValue("time_start",DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间data.SetValue("time_expire",DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")) ;//交易结束时间data.SetValue("goods_tag", "");//商品标记data.SetValue("trade_type", "NATIVE");//交易类型data.SetValue("product_id", "1234");//商品IDWxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接var jsonData = new{url = HttpUtility.UrlEncode(url)};return Success(jsonData);}//将url转换为二维码图片public void CodeConversionT ool(string str){//初始化二维码生成工具QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;qrCodeEncoder.QRCodeVersion = 0;qrCodeEncoder.QRCodeScale = 4;//将字符串生成二维码图片Bitmap image = qrCodeEncoder.Encode(str, Encoding.Default);//保存为PNG到内存流MemoryStream ms = new MemoryStream();image.Save(ms, ImageFormat.Png);//输出二维码图片Response.BinaryWrite(ms.GetBuffer());Response.End();}前台代码:$.lrSetForm(top.$.rootUrl + 'Test/GetPayUrl',function (data) { $("#img").attr("src",top.$.rootUrl + '/Test/CodeConversionT ool?str=' + data.url);});回调方法:public string WxPayNotify(){WePayReturnModel payResult = new WePayReturnModel();HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统contextHttpRequestBase request = context.Request;//定义传统request对象bool result = VerifyNotify(request, out payResult);if (result){//业务代码////////////////////////////////////////////////////如果成功,告知微信不用再调用回调方法WxPayData res = new WxPayData();res.SetValue("transaction_id", payResult.TradeNo);res.SetValue("return_code", "SUCCESS");res.SetValue("return_msg", "OK");return res.ToXml();}else{return "fail";}}这里有一些需要注意的地方,回调地址是区分大小写的,而且一定要用post,不支持get。

微信支付demo

微信支付demo

微信⽀付demo这⾥开发时使⽤的是thinkphp5.11.直接唤起微信⽀付<?phpnamespace app\index\controller;use wechatpay\lib\WxPayApi;use wechatpay\lib\WxPayUnifiedOrder;use wechatpay\example\JsApiPay;use wechatpay\example\WxPayConfig;use think\facade\Env;class Pay{/*1、交易⾦额交易⾦额默认为⼈民币交易,接⼝中参数⽀付⾦额单位为【分】,参数值不能带⼩数。

对账单中的交易⾦额单位为【元】。

外币交易的⽀付⾦额精确到币种的最⼩单位,参数值不能带⼩数点。

2、交易类型JSAPI--公众号⽀付、NATIVE--原⽣扫码⽀付、APP--app⽀付,统⼀下单接⼝trade_type的传参可参考这⾥MICROPAY--刷卡⽀付,刷卡⽀付有单独的⽀付接⼝,不调⽤统⼀下单接⼝3、货币类型货币类型的取值列表:CNY:⼈民币4、时间标准北京时间,时区为东⼋区;如果商户的系统时间为⾮标准北京时间。

参数值必须根据商户系统所在时区先换算成标准北京时间,例如商户所在地为0时区的伦敦,当地时间为2014年11⽉11⽇0时0分0秒,换算成北京时间为2014年11⽉11⽇8时 5、时间戳标准北京时间,时区为东⼋区,⾃1970年1⽉1⽇ 0点0分0秒以来的秒数。

注意:部分系统取到的值为毫秒级,需要转换成秒(10位数字)。

6、商户订单号商户⽀付的订单号由商户⾃定义⽣成,仅⽀持使⽤字母、数字、中划线-、下划线_、竖线|、星号*这些英⽂半⾓字符的组合,请勿使⽤汉字或全⾓等特殊字符。

微信⽀付要求商户订单号保持唯⼀性(建议根据当前系统时间加随机序列来⽣成订单号) *//*** 微信⽀付调⽤* @author ffx* @param int $userId ⽤户id* @param float $money ⾦额* @param int $type ⽀付类型(1充值,2订单⽀付)* @param string $body 显⽰title,提⽰头信息* @param string $backUrl 回调地址(/index/pay/wxPayBack)* @param string $addition 附加参数(微信回调时原样返回)* @return bool|mixed*/public function wxPay($userId,$money,$type,$body,$backUrl,$addition = ''){$out_trade_no = self::getOrderNo();$wxchid = config('wechat.wxmchid');$wxAppId = config('wechat.paywxAppId');//微信⽀付sdk中的⽂件include_once EXTEND_PATH."wechatpay/lib/WxPay.Api.php";include_once EXTEND_PATH."wechatpay/example/WxPay.JsApiPay.php";$total_money = floor(sprintf("%0.3f",$money)*100);if(!$total_money || $total_money <= 0){return ['code'=>100001,'message'=>"⽀付⾦额⼩于0"];}if($_SERVER["REQUEST_SCHEME"] == "http"){$notify_url = 'http://'.$_SERVER['HTTP_HOST'].$backUrl;}else{$notify_url = 'https://'.$_SERVER['HTTP_HOST'].$backUrl;}//此处查询的是登录时存起来的openid$openid = Db::name('member')->where('id',$userId)->value('openid');$input = new \WxPayUnifiedOrder();$input->SetAppid($wxAppId);$input->SetMch_id($wxchid); //商户号$input->SetAttach($addition); //附加参数$nonceStr = self::createNonceStr();$input->SetNonce_str($nonceStr);//⾃定义随机字符串$input->SetBody($body);//$input->SetOut_trade_no($out_trade_no);//订单号,⾃⼰建$input->SetTotal_fee($total_money);//⾦钱$input->SetSpbill_create_ip($this->getIP());//客户端ip$input->SetTime_start(date("YmdHis"));$input->SetTime_expire(date("YmdHis", time() + 600));//过期时间$input->SetNotify_url($notify_url);//回调的接⼝地址$input->SetTrade_type("JSAPI");//⽀付类型$input->SetOpenid($openid);//此处两个是微信⽀付的sdk的类$WxPayApi = new WxPayApi();$config = new WxPayConfig();$response = $WxPayApi->unifiedOrder($config,$input);//预创建订单//写⼊⽀付记录表(业务逻辑处理)$res = $this->insertWxPayLog($userId,$out_trade_no,$money,$type,0);if(!$res){return false;}if($response['result_code']=='SUCCESS' && $response['return_code']=='SUCCESS' && $response['return_msg']=='OK') {$tools = new JsApiPay();$response['nonce_str'] = $nonceStr;$jsApiParameters = $tools->GetJsApiParameters($response);return json_decode($jsApiParameters);//$jsApiParameters⽰例//{"appId":"wx194a1075c8bca3d9","nonceStr":"4tmc7nttscu5w6u6cqbxlgvum4qs6p8y","package":"prepay_id=wx05155440194924091e0efc912670185750","signType":"MD5","timeStamp":"1541404480","paySign":"CD4DE57A6B5B2B5418 //输出直接唤起⽀付// $str = "<html><body></body></html>";//// $str .='<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>微信⽀付</title></head><body>';//// $str .= "<script>function onBridgeReady(){WeixinJSBridge.invoke('getBrandWCPayRequest',$jsApiParameters)}if(typeof WeixinJSBridge=='undefined'){if(document.addEventListener){document.addEventListener('WeixinJSBridgeReady',o//// echo $str;exit;}else{return false;}}/*** 余额⽀付回调* @author ffx**/function amountPayBack(){$xml = file_get_contents('php://input');$xmlJson = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));$arr = json_decode($xmlJson, true);//此处注释暂未⽤到/* //⽤户http_build_query()将数据转成URL键值对形式$sign = http_build_query($arr);//md5处理$sign = md5($sign);//转⼤写$sign = strtoupper($sign);//验签名。

微信支付与支付宝支付的对比分析

微信支付与支付宝支付的对比分析

微信支付与支付宝支付的对比分析随着移动支付的兴起,微信支付和支付宝支付成为了人们生活中不可或缺的一部分。

无论是在线购物、线下消费还是转账支付,微信支付和支付宝支付都提供了便捷的解决方案。

然而,微信支付和支付宝支付之间存在一些差异。

本文将对微信支付和支付宝支付进行对比分析,从用户体验、安全性、功能和商家支持等方面来探讨两者的优劣势。

首先,从用户体验方面来看,微信支付和支付宝支付都提供了简单易用的界面和操作流程。

微信支付通过扫描二维码或者点击链接即可完成支付,而支付宝支付则需要用户输入支付密码或者使用指纹识别等方式进行验证。

从操作上来说,微信支付更加便捷,但支付宝支付在安全性方面更有保障。

其次,安全性是人们选择支付方式时非常重要的考虑因素。

微信支付和支付宝支付都采用了多重安全防护措施,如手机绑定、短信验证和支付密码等。

然而,支付宝支付在安全性方面更加严格,采用了更多的技术手段来保护用户的资金安全。

此外,支付宝支付还提供了实名认证和风险控制系统,进一步提高了支付的安全性。

在功能方面,微信支付和支付宝支付都提供了丰富的功能。

微信支付除了可以用于线上购物和转账支付外,还可以用于线下消费、公共交通等。

支付宝支付则提供了更多的服务,如信用卡还款、水电煤缴费、理财等。

支付宝支付的功能更加全面,满足了用户多样化的需求。

最后,商家支持也是选择支付方式时需要考虑的因素之一。

微信支付和支付宝支付都为商家提供了便捷的支付解决方案,可以通过扫码支付、POS机和网页支付等方式来接收付款。

然而,支付宝支付在商家支持方面更胜一筹,拥有更多的商家合作伙伴和更广泛的应用场景。

综上所述,微信支付和支付宝支付在用户体验、安全性、功能和商家支持等方面都有各自的优劣势。

微信支付更加便捷,适用于日常生活中的各种场景;支付宝支付更加安全,提供了更多的功能和商家支持。

因此,在选择支付方式时,用户可以根据自己的需求和偏好来进行选择。

无论是微信支付还是支付宝支付,都为人们的支付生活带来了极大的便利。

电商平台的支付宝与微信支付对比

电商平台的支付宝与微信支付对比

电商平台的支付宝与微信支付对比随着电子商务的迅速发展,支付方式也变得多样化。

作为中国两大互联网巨头,支付宝和微信支付成为了人们最常用的在线支付工具。

然而,在支付方式的选择上,很多人还是不知道该如何做决策。

那么,接下来我们将对支付宝和微信支付进行对比,以帮助您更好地选择适合自己的付款方式。

一、支付方式支付宝和微信支付都可以通过手机APP、网页和被扫码进行支付。

支付宝以“支付即时到账”的方式来实现快捷支付,而微信支付则是通过关联用户的银行卡或信用卡来完成支付过程。

二、使用范围支付宝支付是阿里巴巴集团旗下的支付平台,主要用于在淘宝、天猫等阿里系电商平台进行支付。

而微信支付则是腾讯旗下的支付平台,主要用于微信内的商家交易付款和线下场景的移动支付。

三、便捷性在支付方式的便捷性上,支付宝和微信支付都有各自的优点。

支付宝在用户注册和绑定银行卡方面相对简单,用户可以通过手机号码和身份证等个人信息完成注册,并将银行卡绑定到支付宝账户上。

而微信支付则更加注重与微信生态系统的一体化,在用户在微信内完成注册后,可以直接关联自己的银行卡进行支付。

四、安全性安全性是在线支付最重要的考量之一。

支付宝采用了严密的安全策略,包括支付密码、手机短信验证码、指纹识别等多重验证机制,保障用户支付的安全性。

而微信支付则通过和腾讯旗下其他产品的结合,采用了安全防护技术,有效防范了支付风险。

五、用户体验支付宝和微信支付在用户体验方面也有所区别。

支付宝致力于提供更加个性化的服务,用户可以通过支付宝APP查看账单、理财投资等功能。

而微信支付则着重于社交属性的发展,用户可以在微信内直接发起红包、转账等操作,并与好友分享付款体验。

六、手续费对于商家而言,手续费也是考虑选择支付方式的一个因素。

支付宝和微信支付的手续费相对接近,一般为交易金额的0.6%-0.8%左右。

然而,具体的费用还会根据不同的行业和交易金额而有所不同。

综合上述对比,我们可以看出支付宝和微信支付各有优势,选择哪一种支付方式取决于您的需求和偏好。

电子支付知识:支付宝和微信支付的使用方法和功能介绍

电子支付知识:支付宝和微信支付的使用方法和功能介绍

电子支付知识:支付宝和微信支付的使用方法和功能介绍随着移动支付的普及,支付宝和微信支付成为了广大用户生活不可或缺的两个应用。

本文将介绍这两款电子支付的使用方法和功能。

一、支付宝使用方法及功能介绍1.注册登录下载支付宝APP后,注册成为支付宝用户并登录账户,用户可以在支付宝个人中心进行操作。

2.添加银行卡添加银行卡后,就可以进行充值和提现操作。

用户的银行卡信息会被加密保护,安全可靠。

3.扫码支付用户可以通过支付宝扫描商家的支付二维码,进行购买物品的支付。

支付宝支持主流银行和各类优惠活动。

4.转账付款用户可以在支付宝内进行转账,支持绑定支付宝账户、手机号、银行卡等多种方式。

该操作简单便捷,可以在任何时候进行。

5.生活缴费支付宝还支持生活缴费服务,包括水、电、燃气、电话、宽带、有线电视等多项服务。

用户只需添加缴费项目,即可随时进行缴费,不必面对繁琐的缴费手续和排队等待。

6.理财产品支付宝还推出了多种理财产品,用户可根据自身需求进行选择。

理财产品收益高、起投金额低,为用户提供良好的理财方式。

二、微信支付使用方法及功能介绍1.注册登录用户需要下载微信APP并进行注册,才能进行微信支付。

用户登录微信后,在个人中心内即可进行操作。

2.添加银行卡用户需要在微信支付内添加银行卡,以便进行充值和提现操作。

微信支付的充值和提现操作需要使用微信钱包进行。

3.扫码支付微信支付也支持扫码支付,用户可以在微信钱包内扫描商家支付码进行购物。

微信支付支持多种行业和商户,使用范围广泛。

4.转账付款微信支付支持用户进行转账付款操作,用户可以通过微信支付给其他用户转账,并且支持多种付款方式。

5.公共服务微信支付还提供了各种公共服务,包括水电煤气缴费、医院挂号、交通违章查询等多项服务。

用户只需要在微信支付内进行添加服务,即可随时进行操作。

6.理财产品微信支付也推出了丰富的理财产品,包括活期、定期、基金等多种方式。

用户可以根据自身需求进行选择,实现理财增值。

微信支付PHP开发:微信支付代码及获取支付成功数据

微信支付PHP开发:微信支付代码及获取支付成功数据

微信支付PHP开发一:微信支付代码及获取支付成功数据一、微信支付demo代码<?phpinclude_once("include/WxPayHelper.php"); //该文件微信DEMO包中有,没有请到官网上下载$commonUtil = new CommonUtil();$wxPayHelper = new WxPayHelper();$user_ip= $_SERVER["REMOTE_ADDR"];$wxPayHelper->setParameter("bank_type", "WX");$wxPayHelper->setParameter("body", "微信支付测试");$wxPayHelper->setParameter("partner", "11111111");$wxPayHelper->setParameter("out_trade_no", $commonUtil->create_noncestr()); $wxPayHelper->setParameter("total_fee", "1");$wxPayHelper->setParameter("fee_type", "1");$wxPayHelper->setParameter("notify_url", "/wxpay/api.php"); $wxPayHelper->setParameter("spbill_create_ip", $user_ip);$wxPayHelper->setParameter("input_charset", "UTF-8");?><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta content="application/xhtml+xml;charset=UTF-8" http-equiv="Content-Type"><meta content="no-cache,must-revalidate" http-equiv="Cache-Control"><meta content="no-cache" http-equiv="pragma"><meta content="0" http-equiv="expires"><meta content="telephone=no, address=no" name="format-detection"><meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1,minimum-scale=1, width=device-width, height=device-height" /><meta name="apple-mobile-web-app-capable" content="yes" /> <!-- apple devices fullscreen --><meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /><title>在线支付测试</title></head><script language="javascript">function callpay(){WeixinJSBridge.invoke('getBrandWCPayRequest',<?php echo$wxPayHelper->create_biz_package(); ?>,function(res){if(res.err_msg == "get_brand_wcpay_request:ok" ){// 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。

微信APP支付,支付宝APP支付demo

微信APP支付,支付宝APP支付demo

微信APP⽀付,⽀付宝APP⽀付demo最近公司新开发的APP中,需要集成微信⽀付和⽀付宝⽀付,2个平台申请的都是APP⽀付。

这是个⼈第⼀次单独的,完整的做完2个平台的⽀付。

这⾥我主要⽤到了2个接⼝:⽀付接⼝,订单查询接⼝,虽然2个平台的⽂档都挺齐全,但开发下来,还是踩了不少坑,记录下来,或许对后来⼈有⽤。

先来说⽀付宝SDK: 了解3个概念:应⽤公钥,应⽤私钥和⽀付宝公钥 开发⼈员⽤⽀付宝提供的秘钥⽣成⼯具⽣成的秘钥,即为应⽤公钥和应⽤私钥。

开发⼈员在给⽀付宝APP配置应⽤公钥后,⽀付宝主动⽣成了⼀个公钥,即为⽀付宝公钥。

配置如下图⽰: 需要把这个⽀付宝公钥保存下来,具体使⽤场景,请看后续说明。

这⾥个⼈⽤到了2个接⼝,⽣成⽀付订单信息和订单查询。

⽀付宝提供了服务端SDK的下载: 其⽬录显⽰: 下⾯直接给出⽀付、回调、订单查询的代码:// ⽣成⽀付信息function pay() {$aop = new AopClient;$aop->gatewayUrl = '⽹关地址';$aop->appId = 'alipay_appid';$aop->rsaPrivateKey = '应⽤私钥';$aop->signType = "RSA2";$aop->alipayrsaPublicKey = '⽀付宝公钥';$request = new AlipayTradeAppPayRequest();$bizcontent = "{\"body\":\"账户充值\",". "\"subject\": \"⽤户账户充值\",". "\"out_trade_no\": \"订单号\",". "\"timeout_express\": \"30m\",". "\"total_amount\": \"订单⾦额\",". "\"product_code\":\"QUICK_MSECURITY_PAY\"". "}";$request->setNotifyUrl('开发者回调地址');$request->setBizContent($bizcontent);$response = $aop->sdkExecute($request);// 注意:官⽅demo⾥,这⾥加了htmlspecialchars⽅法,其实是错误的,应该去掉,否则会报ALI38173错误 echo $response;}// 回调function callback() {$aop = new AopClient ();$aop->alipayrsaPublicKey = '⽀付宝公钥';// ⽀付宝回调是以POST⽅式提交过来的$result = $aop->rsaCheckV1($_POST, null, $_POST['sign_type']);if ($result) {// TODO 验证订单号,⽀付⾦额,⽀付宝状态等信息echo 'success';} else {echo 'error';}}// 订单查询function queryOrder() {$aop = new AopClient ();$aop->signType = "RSA2";$aop->gatewayUrl = '⽹关地址';$aop->appId = 'appid';$aop->rsaPrivateKey = '应⽤私钥';// 注意:这⾥是⽀付宝公钥,不是应⽤公钥$aop->alipayrsaPublicKey = '⽀付宝公钥';$request = new AlipayTradeQueryRequest ();$request->setBizContent("{" ."\"out_trade_no\":\"订单号\"," ."\"trade_no\":\"交易单号\"" ."}");$result = $aop->execute($request);$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";$resultCode = $result->$responseNode->code;if(! empty($resultCode) && $resultCode == 10000) {if ($result->$responseNode->trade_status == 'TRADE_SUCCESS') {// ⽀付成功, 更新订单状态,⽤户账户余额,账户变化⽇志}}}微信⽀付: 在开发平台申请app⽀付: 审核通过后,需要配置开发信息 服务端PHP的demo:// ⽣成⽀付信息function pay() {$input = new WxPayUnifiedOrder();$input->SetBody('⽀付标题');$input->SetAttach('附加信息'); // 附加信息$input->SetOut_trade_no('订单号');$input->SetTotal_fee('订单⾦额,单位分'); //微信⽀付,单位(分)$input->SetTime_start(date("YmdHis"));$input->SetTime_expire(date("YmdHis", time() + 600));$input->SetGoods_tag('附属信息');$input->SetNotify_url('回调地址');$input->SetTrade_type("APP");// ⽣成预⽀付订单ID:prepay_id$unifiedOrder = WxPayApi::unifiedOrder($input);// ⽣成签名,返回给APP前端调⽤$result = makeWxPaySign($unifiedOrder);}// ⽣成签名function makeWxPaySign($UnifiedOrderResult){if(! array_key_exists("appid", $UnifiedOrderResult)|| ! array_key_exists("prepay_id", $UnifiedOrderResult)|| empty($UnifiedOrderResult['prepay_id'])){throw new WxPayException("参数错误");}$api = new WxPayAppPay();$api->SetValue('appid', $UnifiedOrderResult["appid"]);$api->SetValue('package', "Sign=WXPay");$api->SetValue('prepayid', $UnifiedOrderResult['prepay_id']); // 预⽀付订单号$api->SetValue('partnerid', WxPayConfig::MCHID); // 商户号$api->SetValue('noncestr', WxPayApi::getNonceStr()); // 随机数$api->SetValue('timestamp', (string)time());// 对上⾯参数进⾏签名$api->SetValue('sign', $api->MakeSign());return$api->GetValues();}// 回调,继承微信SDK的回调类class PayNotifyCallBack extends WxPayNotify{//重写回调处理函数public function NotifyProcess($data, &$msg){if (! array_key_exists("transaction_id", $data)) {return false;}// 调⽤订单查询⽅法,判断订单真实性return true;}}// 订单查询function queryOrder() {$input = new WxPayOrderQuery();$input->SetTransaction_id('⽀付平台交易号');$input->SetOut_trade_no('公司平台单号');// 订单查询结果$result = WxPayApi::orderQuery($input);if(array_key_exists("return_code", $result)&& array_key_exists("result_code", $result)&& array_key_exists('trade_state', $result)&& $result["return_code"] == "SUCCESS"&& $result["result_code"] == "SUCCESS"&& $result["trade_state"] == "SUCCESS"){// 交易成功,todo 更新订单状态,⽤户账户余额,账户变化⽇志 }}。

如何选择适合的支付方式来经营网店

如何选择适合的支付方式来经营网店

如何选择适合的支付方式来经营网店在互联网时代,越来越多的人选择开设网店,从事电子商务。

而支付方式是网店经营中至关重要的一环。

选择适合的支付方式,不仅可以提高用户购物的便捷性,还可以保障交易的安全性。

本文将为你介绍如何选择适合的支付方式来经营网店。

一、了解常见的支付方式在选择适合的支付方式之前,我们需要了解几种常见的支付方式,包括支付宝、微信支付、银联在线支付等。

支付宝和微信支付作为中国最主要的第三方支付平台,在网店经营中被广泛使用。

支付宝:拥有庞大的用户群体,在国内电子商务交易中应用广泛。

支付宝提供多种支付方式,包括扫码支付、手机支付和网页支付等,方便用户进行在线交易。

微信支付:与支付宝类似,微信支付是由微信平台提供的支付服务。

用户可以通过微信扫一扫完成支付,也可以在网页上使用微信支付进行交易。

银联在线支付:银联在线支付是由中国银联提供的一种在线支付方式,可以通过网银支付、手机银行支付等方式进行交易。

相比于第三方支付平台,银联在线支付更注重交易的安全性。

二、考虑用户需求选择适合的支付方式,需要考虑到用户的需求。

不同的用户有不同的支付习惯和支付方式偏好。

通过调查研究和用户反馈,可以更好地了解用户的需求。

例如,如果你的网店主要面向年轻人群体,那么支付宝和微信支付可能会更适合,因为年轻人更习惯使用移动支付方式。

而如果你的网店主要面向中老年用户,那么银联在线支付可能更符合他们的需求。

三、综合考虑安全性和成本在选择支付方式时,安全性和成本也是两个重要的考虑因素。

安全性:交易的安全性对于网店经营来说至关重要。

选择有良好安全记录的支付平台可以降低交易风险。

例如,支付宝和微信支付经过多年的发展和实践,具备较高的安全性。

成本:不同的支付方式会有不同的费率和手续费。

商家需要考虑自己的经营规模和利润情况,选择最经济实惠的支付方式。

同时,还要了解支付方式对于提现的限制和费用等因素。

四、考虑平台支持和服务在选择支付方式时,考虑支付平台的支持和服务也是很重要的。

PHP微信扫码支付DEMO,thinkphp5+微信支付

PHP微信扫码支付DEMO,thinkphp5+微信支付

PHP微信扫码⽀付DEMO,thinkphp5+微信⽀付PS:微信⽀付基础条件1.⼀个认证的服务号2.在服务号后台申请微信⽀付,成功后获得⼀个商户号3.在商户号⾥⾯选择native⽀付,这个就是扫码⽀付,按照提⽰开通这项。

4.按照微信⽀付⽂档的说法,扫码⽀付分两种模式模式⼀:⽣成的⼆维码没有失效性,但是操作⽐较复杂,中间步骤⽐较多,容易出现很多问题。

模式⼆:⽣成的⼆维码有两⼩时时间限制,但是我感觉也⼗分够⽤了,这个步骤⽐较简单,很容易实现。

按照时序图,⼤概也就分两步代码结构:配置⽂件:微信⽀付类:<?php/** To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates* and open the template in the editor.*/namespace tools;use think\Config;/*** Description of WxPay** @author admin*/class WxPay {/*** 获取签名* @param type $arr* @return type*/public function getSign($arr)//去除数组的空值array_filter($arr);if(isset($arr['sign'])){unset($arr['sign']);}//排序ksort($arr);//组装字符$str = $this->arrToUrl($arr) . '&key=' . Config::get('wx_pay')['key'];//使⽤md5 加密转换成⼤写return strtoupper(md5($str));}/*** 校验签名* @param type $arr* @return boolean*/public function checkSign($arr){//⽣成新签名$sign = $this->getSign($arr);//和数组中原始签名⽐较if($sign == $arr['sign']){return true;}else{return false;}}/*** 获取带签名的数组* @param array $arr* @return type*/public function setSign($arr){$arr['sign'] = $this->getSign($arr);return $arr;}/*** 数组转URL字符串不带key* @param type $arr* @return type*/public function arrToUrl($arr){return urldecode(http_build_query($arr));}/*** 记录到⽂件* @param type $file* @param type $data*/public function logs($file,$data){$data = is_array($data) ? print_r($data,true) : $data;file_put_contents('./public/paylogs/' .$file, $data);}/*** 接收POST推送* @return type*/public function getPost(){return file_get_contents('php://input');}/*** Xml ⽂件转数组* @param type $xml* @return string*/public function XmlToArr($xml){if($xml == '') return'';libxml_disable_entity_loader(true);$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);return $arr;}/*** 数组转XML* @param type $arr* @return string*/public function ArrToXml($arr){if(!is_array($arr) || count($arr) == 0) return'';$xml = "<xml>";foreach ($arr as $key=>$val){if (is_numeric($val)){$xml.="<".$key.">".$val."</".$key.">";}else{$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";}}$xml.="</xml>";return $xml;}/*** 发送POST请求* @param type $url* @param type $postfields* @return typepublic function postStr($url,$postfields){$ch = curl_init();$params[CURLOPT_URL] = $url; //请求url地址$params[CURLOPT_HEADER] = false; //是否返回响应头信息$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回$params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向$params[CURLOPT_POST] = true;$params[CURLOPT_SSL_VERIFYPEER] = false;//禁⽤证书校验$params[CURLOPT_SSL_VERIFYHOST] = false;$params[CURLOPT_POSTFIELDS] = $postfields;curl_setopt_array($ch, $params); //传⼊curl参数$content = curl_exec($ch); //执⾏curl_close($ch); //关闭连接return $content;}/*** 统⼀下单* @param type $params* @return boolean*/public function unifiedorder($params){//获取到带签名的数组$params = $this->setSign($params);//数组转xml$xml = $this->ArrToXml($params);//发送数据到统⼀下单API地址$data = $this->postStr(Config::get('wx_pay')['uourl'], $xml);$arr = $this->XmlToArr($data);if($arr['result_code'] == 'SUCCESS' && $arr['return_code'] == 'SUCCESS'){return $arr;}else{$this->logs('error.txt', $data);return false;}}}index控制器演⽰代码<?phpnamespace app\index\controller;use app\common\controller\HomeBase;use tools\WxPay;use think\Config;use phpqrcode\ApiQrcode;use think\Request;use think\Cache;use tools\RetJosn;class Index extends HomeBase {/*** ⾸页* @param WxPay $wxpay* @return mixed*/public function index(WxPay $wxpay) {//$wxpay->logs('log.txt',['213123','123123123']);echo 'index';}/*** 扫码⽀付-模式⼆* @param WxPay $wxpay*/public function index2(Request $request, WxPay $wxpay) {if ($request->isGet()) {return $this->fetch();}}/*** 统⼀下单,⽣成⼆维码*/public function getQrUrl(Request $request) {$pid = $request->get('id');//调⽤统⼀下单API$params = ['appid' => Config::get('wx_pay')['appid'],'mch_id' => Config::get('wx_pay')['mchid'],'nonce_str' => md5(time()),'body' => '订单号:'.$pid,'out_trade_no' => $pid,'total_fee' => 2,'spbill_create_ip' => $_SERVER['SERVER_ADDR'],'notify_url' => Config::get('wx_pay')['notify'],'trade_type' => 'NATIVE','product_id' => $pid];$wxpay = new WxPay();$arr = $wxpay->unifiedorder($params);if (!empty($arr['code_url'])) {Cache::set('send' . $params['out_trade_no'], $params['total_fee'], 3600); ApiQrcode::png($arr['code_url']);} else {return'下单失败!';}}/*** 接收腾讯推送⽀付通知* @param WxPay $wxpay*/public function backOrder(WxPay $wxpay) {try {// 获取腾讯传回来的通知数据$xml = $wxpay->getPost();// 将XML格式的数据转换为数组$arr = $wxpay->XmlToArr($xml);$wxpay->logs('logs.txt', '1');// 验证签名if ($wxpay->checkSign($arr)) {Cache::set('back'.$arr['out_trade_no'],$arr['total_fee'],3600);}$wxpay->logs('logs.txt', '2');$params = ['return_code' => 'SUCCESS','return_msg' => 'OK'];echo $wxpay->ArrToXml($params);} catch (\Exception $e) {$wxpay->logs('logs.txt', $e->getMessage());exit();}}/*** 查询⽀付状态* @param Request $request* @return type*/public function checkSuccess(Request $request){$pid = $request->get('id');if (Cache::get('send'.$pid) == Cache::get('back'.$pid)) {return RetJosn::successJson('⽀付成功');} else {return RetJosn::errorJson(Cache::get('send'.$pid).'|'.Cache::get('back'.$pid)); }}}⼆维码页⾯代码:<!DOCTYPE html><!--To change this license header, choose License Headers in Project Properties.To change this template file, choose Tools | Templatesand open the template in the editor.--><html><head><title>TODO supply a title</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><div class="btn-box"><button onclick="getQrcode()">刷新⼆维码</button></div><div class="qrcode-box"><img id="qrimg" src=""></div><div class="status-box"><h2 id="status"></h2></div></body><script src="__STATIC__/default/js/jquery-1.9.1.min.js"></script><script>(function () {getQrcode();//⼆维码⽣成})();/*验证码⽣成*/function getQrcode() {var id = getId(10);var url = "{:url('Index/getQrUrl')}" + "?id=" + id;$("#qrimg").attr("src", url);sessionStorage.setItem('id',id);checkSuccess();//轮询⽀付状态}/*⽣成唯⼀Id*/function getId(length){var tmp = Date.parse( new Date() ).toString();tmp = tmp.substr(0,length);return tmp;}/*轮询⽀付状态*/function checkSuccess(){var interval = window.setInterval(function(){var id = sessionStorage.getItem('id');$.ajax({url:"{:url('Index/checkSuccess')}?id=" + id,dataType:'json',success:function(res) {if (res.code == 200) {$('#status').html('订单号:'+id+','+res.msg); clearInterval(interval);}}})},2000)}</script></html>效果演⽰:⽣成⼆维码,并开始启动轮询⼿机上⽀付订单:轮询到成功⽀付的状态:。

微信支付开发教程附demo链接

微信支付开发教程附demo链接

The Art of NegotiationNegotiation is an art form that requires a combination of skills, tactics, and strategies to achieve a mutually beneficial outcome. It is a process that involves two or more parties coming together to discuss and ultimately reach an agreementon a particular issue or dispute. The ability to negotiate effectively is a valuable skill that can be applied in various aspects of life, whether it be in business, personal relationships, or even everyday interactions. One of the key elements of successful negotiation is the ability to communicate effectively. This involves not only expressing your own needs and interests clearly but alsoactively listening to the other party's perspective. By understanding the motivations and concerns of the other party, you can tailor your approach and arguments to better align with their interests. This can help build rapport and trust, ultimately leading to a more collaborative and productive negotiation process. Another important aspect of negotiation is the ability to remain calmand composed under pressure. Emotions can often run high during negotiations, especially when there are conflicting interests at stake. It is crucial tomaintain a level head and avoid reacting impulsively to any provocations or challenges that may arise. By staying focused and composed, you can think more clearly and make rational decisions that are in your best interest. Furthermore, preparation is key to successful negotiation. Before entering into any negotiation, it is important to do your homework and gather as much information as possible about the other party, the issue at hand, and potential solutions. This can help you anticipate the other party's arguments and objections, allowing you to come up with counterarguments and alternative solutions in advance. By being well-prepared, you can enter the negotiation with confidence and a clear strategy in mind. Flexibility is another important trait to possess during negotiations. While it is important to have a clear goal and desired outcome in mind, it is also importantto be open to compromise and alternative solutions. Negotiation is a give-and-take process, and being too rigid or inflexible in your demands can hinder the progress of the negotiation and lead to an impasse. By being open to new ideas and creative solutions, you can increase the likelihood of reaching a mutually beneficial agreement. In addition, it is important to be aware of your own strengths andweaknesses during negotiations. Understanding your own negotiation style, strengths, and areas for improvement can help you play to your strengths and mitigate your weaknesses. For example, if you are a strong communicator but lack patience, you can work on developing your patience skills and practicing active listening to improve your overall negotiation effectiveness. Self-awareness is key to becoming a more effective negotiator. Lastly, it is important to remember that negotiation is not a zero-sum game. It is possible for both parties to walk away from a negotiation feeling satisfied with the outcome. By focusing on creating value and finding common ground, rather than simply trying to outmaneuver the other party, you can build trust and goodwill that can lead to successful future negotiations. Ultimately, negotiation is about finding creative solutions to complex problems and working together towards a mutually beneficial agreement.。

微信、支付宝二码合一扫码支付实现思路(java)

微信、支付宝二码合一扫码支付实现思路(java)

微信、⽀付宝⼆码合⼀扫码⽀付实现思路(java)⼀、⽀付⼆维码(预订单)根据需要购买的信息创建预订单,将订单信息保存到Redis中,并设置有效期,注意⽣产⼆维码的链接后的参数可以关联到Redis中的key;QRCode 为servlet扫码请求的URL;UUIDUtils.getUUID() 为预订单单号,在servlet请求中截取,然后在Redis中查找对应的Key的数据;⼆、创建⼆维码扫码请求地址servlet:QRCodeServlet;微信⽀付重定向请求servlet:WechatPayServlet;⽀付宝重定向请求servlet:AliPayServlet;QRCodeServlet ⽤于⽤户使⽤微信或者⽀付宝扫码⼆维码进⾏客户端识别及重定向到对应的业务处理;package com.platform.cloudlottery.servlet;import java.io.IOException;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.context.support.SpringBeanAutowiringSupport;import monConfig;import mon.alipay.config.MyAliPayConfig;import mon.wechat.config.WXPublicConfig;import mon.wechat.util.HttpUtil;import com.platform.cloudlottery.model.SysPayChannel;import com.platform.cloudlottery.service.Impl.SysPayChannelServiceImpl;import com.platform.cloudlottery.web.StatusContant.PayTypeConstant;/*** @ClassName: QRCodeServlet* @Description: TODO(根据请求的后缀获取该数据编码对应的数据,并重定向到页⾯)* @author chenkun* @date 2018年12⽉29⽇**/public class QRCodeServlet extends HttpServlet {private static final long serialVersionUID = -8457626626670970403L;protected Logger logger = LoggerFactory.getLogger(getClass());private static final String UrlStr = "QRCode/";private static final String wechatPay = "wechatPay/";private static final String aliPay = "aliPay/";@Autowiredprivate SysPayChannelServiceImpl payChannelService;public void init(ServletConfig servletConfig) throws ServletException {super.init(servletConfig);SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, servletConfig.getServletContext());}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {("####################请求开始####################");String userAgent = request.getHeader("user-agent");String RequestURL = request.getRequestURL().toString();("URL : " + RequestURL);String ReqInfo = RequestURL.substring(RequestURL.indexOf(UrlStr)+UrlStr.length());("URL : " + ReqInfo);CommonConfig commonConfig = new CommonConfig();if (userAgent != null && userAgent.contains("AlipayClient")) {("来⾃⽀付宝");String redirecturi = HttpUtil.urlEnCode(commonConfig.getDomain() + aliPay + ReqInfo);("REDIRECT_URI="+redirecturi);SysPayChannel channel = payChannelService.selectByChannelType(PayTypeConstant.Alipay);MyAliPayConfig aliPayConfig = new MyAliPayConfig();aliPayConfig.setAppId(channel.getAppid());// 授权页⾯地址String requestUrl = aliPayConfig.getAuthgateway();requestUrl = requestUrl.replace("APPID", aliPayConfig.getAppId()).replace("SCOPE", aliPayConfig.getScope()).replace("REDIRECT_URI", redirecturi);// 重定向到授权页⾯response.sendRedirect(requestUrl);} else if (userAgent != null && userAgent.contains("MicroMessenger")) {("来⾃微信");String redirecturi = HttpUtil.urlEnCode(commonConfig.getDomain() + wechatPay + ReqInfo);("REDIRECT_URI="+redirecturi);SysPayChannel channel = payChannelService.selectByChannelType(PayTypeConstant.Wechat);WXPublicConfig publicConfig = new WXPublicConfig();publicConfig.setAppId(channel.getAppid());publicConfig.setOriginId(channel.getOriginid());publicConfig.setAppSecret(channel.getAppsecret());publicConfig.setEncodingAESKey(channel.getEncodingaeskey());// 授权页⾯地址String requestUrl = publicConfig.getAuthorizeinterface();requestUrl = requestUrl.replace("APPID", publicConfig.getAppId()).replace("REDIRECT_URI", redirecturi).replace("SCOPE", publicConfig.getScope()).replace("STATE", publicConfig.getState()); // 重定向到授权页⾯response.sendRedirect(requestUrl);} else {("未知来源");}("####################请求结束####################");}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}WechatPayServlet 在获取到Redis中预订单数据后,创建真实订单并调⽤微信“统⼀下单接⼝”;package com.platform.cloudlottery.servlet;import com.alibaba.fastjson.JSONObject;import com.github.wxpay.sdk.WXPayUtil;import monConfig;import mon.jedis.JedisUtil;import ng.StringUtils;import mon.utils.BusinessCodeUtils;import mon.wechat.bean.WeiXinOAuth2Token;import mon.wechat.bean.WeiXinUserInfo;import mon.wechat.config.WXPayConfig;import mon.wechat.config.WXPublicConfig;import mon.wechat.util.WeiXinOAuth2Util;import mon.wechat.util.WeiXinPayUtils;import com.platform.cloudlottery.model.SysPayChannel;import com.platform.cloudlottery.service.Impl.LotteryOrderServiceImpl;import com.platform.cloudlottery.service.Impl.SysPayChannelServiceImpl;import erMemberServiceImpl;import com.platform.cloudlottery.service.OrderServcie;import erInfoService;import com.platform.cloudlottery.web.ResultContant;import com.platform.cloudlottery.web.StatusContant.PayTypeConstant;import com.platform.cloudlottery.web.SysKey;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.context.support.SpringBeanAutowiringSupport;import redis.clients.jedis.Jedis;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.math.BigDecimal;import java.util.Date;import java.util.LinkedHashMap;import java.util.Map;/*** @ClassName: WechatPayServlet* @Description: TODO(这⾥⽤⼀句话描述这个类的作⽤)* @author chenkun* @date 2019年1⽉5⽇**/public class WechatPayServlet extends HttpServlet {private static final long serialVersionUID = -8457626626670970403L;protected Logger logger = LoggerFactory.getLogger(getClass());private static Jedis redis = JedisUtil.getJedis();@Value("${config.domain}")private String domain;@Value("${config.isProduction}")private boolean isProduction;// 请求路径包含的字符串private static final String UrlStr = "wechatPay/";@Autowiredprivate SysPayChannelServiceImpl payChannelService;@Autowiredprivate UserMemberServiceImpl memberService;@Autowiredprivate LotteryOrderServiceImpl lotteryOrderService;public void init(ServletConfig servletConfig) throws ServletException {super.init(servletConfig);SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, servletConfig.getServletContext());}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {logger.debug("####################请求开始####################");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");try {// ⽤户同意授权后,能获取到codeString code = request.getParameter("code");// ⽤户同意授权if (!"authdeny".equals(code)) {CommonConfig commonConfig = new CommonConfig();String RequestURL = request.getRequestURL().toString();logger.debug("URL : " + RequestURL);String QRCodeUrl = RequestURL.substring(RequestURL.indexOf(UrlStr) + UrlStr.length());String QRCodeReqInfo = QRCodeUrl.split("&")[0];String operatorId = QRCodeUrl.split("&")[1];logger.debug("QRCodeReqInfo : " + QRCodeReqInfo +";operatorId : " + operatorId);String advancekey = commonConfig.getLotteryorder() + QRCodeReqInfo;SysPayChannel channel = payChannelService.selectByChannelType(PayTypeConstant.Wechat);WXPublicConfig publicConfig = new WXPublicConfig();publicConfig.setAppId(channel.getAppid());publicConfig.setOriginId(channel.getOriginid());publicConfig.setAppSecret(channel.getAppsecret());publicConfig.setEncodingAESKey(channel.getEncodingaeskey());WXPayConfig payConfig = new WXPayConfig();payConfig.setMchId(channel.getMchid());payConfig.setAppId(channel.getAppid());payConfig.setKey(channel.getWxkey());payConfig.setApicertPath(channel.getPayCertUrl());payConfig.setSpbillCreateIp(channel.getSpbillcreateip());// 获取⽹页授权access_tokenWeiXinOAuth2Token weixinOauth2Token = WeiXinOAuth2Util.getOAuth2AccessToken(publicConfig,code);// ⽹页授权接⼝访问凭证String accessToken = weixinOauth2Token.getAccessToken();logger.debug("accessToken=" + accessToken);// ⽤户标识String openId = weixinOauth2Token.getOpenId();logger.debug("openId="+openId);// 获取⽤户信息WeiXinUserInfo userInfo = WeiXinOAuth2Util.getOAuth2UserInfo(publicConfig, accessToken, openId);logger.debug(userInfo.getNickName()+"=====微信⽀付====="+userInfo.getOpenId());//添加或更新⽤户信息String userid = UserInfoService.CreateUserMember(userInfo,memberService);if (!redis.exists(advancekey)) {// 判断key是否存在logger.debug("⼆维码失效");request.setAttribute("code", ResultContant.notuserdqrcode);request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);logger.debug("####################请求结束####################");return;}if (StringUtils.trimToEmpty(redis.get(advancekey)).equals("")) {logger.debug("⼆维码失效");request.setAttribute("code", ResultContant.notuserdqrcode);request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);logger.debug("####################请求结束####################");return;}JSONObject jsonObject = JSONObject.parseObject(redis.get(advancekey));if (null == jsonObject) {logger.debug("⼆维码失效");request.setAttribute("code", ResultContant.notuserdqrcode);request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);logger.debug("####################请求结束####################");return;}if (redis.get(advancekey + "_lock") != null && !redis.get(advancekey + "_lock").equals("")){logger.debug("⼆维码失效");request.setAttribute("code", ResultContant.notuserdqrcode);request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);logger.debug("####################请求结束####################");return;}redis.setex(advancekey + "_lock", 1, "lock");String orderid = BusinessCodeUtils.getOrderNo(jsonObject.getString(SysKey.deviceSn));int money = jsonObject.getIntValue(SysKey.money);int lotterytype = jsonObject.getIntValue(SysKey.lotteryType);if (!orderid.equals("") && money!=0) {//创建订单boolean bool = OrderServcie.createorder(QRCodeReqInfo, PayTypeConstant.Wechat, payConfig.getAppID(), userid, openId, orderid, jsonObject, lotteryOrderService); if (bool) {//删除预订单信息redis.del(advancekey);//⼀个预订单只能创建⼀个订单String paymoney = String.valueOf(money);if (!isProduction) {//测试环境paymoney = BigDecimal.valueOf(Long.valueOf(paymoney)).divide(new BigDecimal(100)).toString();//真实⾦额除100}logger.debug("是否⽣产环境:"+isProduction+";订单⾦额为:"+String.valueOf(money)+";实际⽀付⾦额为:"+paymoney);//创建微信订单Map<String, String> map = WeiXinPayUtils.createOrderJsapi(domain, payConfig, orderid, paymoney, lotterytype==0?"即开票":"电脑票", openId);logger.debug("创建微信⽀付预订单返回数据:"+JSONObject.toJSONString(map));if (map != null) {if (map.get("return_code").equals("SUCCESS")) {if (map.get("result_code").equals("SUCCESS")) {logger.debug("创建微信⽀付预订单成功");Map<String, String> data = new LinkedHashMap<String, String>();data.put("appId", payConfig.getAppID());data.put("timeStamp", String.valueOf(new Date().getTime()/1000));data.put("nonceStr", WXPayUtil.generateNonceStr());data.put("package", "prepay_id="+map.get("prepay_id"));data.put("signType", "MD5");data.put("paySign", WXPayUtil.generateSignature(data, payConfig.getKey()));logger.debug("返回到客户端的数据:"+JSONObject.toJSONString(data));request.setAttribute("appId", data.get("appId"));request.setAttribute("timeStamp", data.get("timeStamp"));request.setAttribute("nonceStr", data.get("nonceStr"));request.setAttribute("package", data.get("package"));request.setAttribute("signType", data.get("signType"));request.setAttribute("paySign", data.get("paySign"));request.setAttribute("code", ResultContant.sucess);request.setAttribute("message", "成功");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);}else{logger.debug("创建订单失败:创建⽀付预订单失败");request.setAttribute("code", ResultContant.createordererror);request.setAttribute("message", "创建订单失败");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);}} else {logger.debug("创建订单失败:创建⽀付预订单失败");request.setAttribute("code", ResultContant.createordererror);request.setAttribute("message", "创建订单失败");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);}} else {logger.debug("创建订单失败:创建⽀付预订单失败");request.setAttribute("code", ResultContant.createordererror);request.setAttribute("message", "创建订单失败");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);}} else {logger.debug("创建订单失败:创建⽀付预订单失败");request.setAttribute("code", ResultContant.createordererror);request.setAttribute("message", "创建订单失败");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);}} else {logger.debug("创建订单失败;订单⾦额或者订单号数据有误");request.setAttribute("code", ResultContant.createordererror);request.setAttribute("message", "创建订单失败");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);}}} catch (Exception e) {e.printStackTrace();logger.debug("系统异常");request.setAttribute("code", ResultContant.notuserdqrcode);request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request, response);}logger.debug("####################请求结束####################");}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response);}}AliPayServlet 在获取到Redis中预订单数据后,创建真实订单并调⽤⽀付宝“⼿机⽹站⽀付接⼝”;package com.platform.cloudlottery.servlet;import com.alibaba.fastjson.JSONObject;import monConfig;import mon.alipay.bean.AliPayOAuth2Token;import mon.alipay.bean.AliPayUserInfo;import mon.alipay.config.MyAliPayConfig;import mon.alipay.uitl.AliPayOAuth2Util;import mon.alipay.uitl.AlipayPayUtils;import mon.jedis.JedisUtil;import ng.StringUtils;import mon.properties.PropertiesUtils;import mon.utils.BusinessCodeUtils;import com.platform.cloudlottery.model.SysPayChannel;import com.platform.cloudlottery.service.Impl.LotteryOrderServiceImpl;import com.platform.cloudlottery.service.Impl.SysPayChannelServiceImpl;import erMemberServiceImpl;import com.platform.cloudlottery.service.OrderServcie;import erInfoService;import com.platform.cloudlottery.web.ResultContant;import com.platform.cloudlottery.web.StatusContant.PayTypeConstant;import com.platform.cloudlottery.web.SysKey;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.context.support.SpringBeanAutowiringSupport;import redis.clients.jedis.Jedis;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.math.BigDecimal;import java.util.Properties;/*** @ClassName: AliPayServlet* @Description: TODO(这⾥⽤⼀句话描述这个类的作⽤)* @author chenkun* @date 2019年1⽉5⽇**/public class AliPayServlet extends HttpServlet {private static final long serialVersionUID = -8457626626670970403L;protected Logger logger = LoggerFactory.getLogger(getClass());private static Jedis redis = JedisUtil.getJedis();@Value("${config.domain}")private String domain;@Value("${config.isProduction}")private boolean isProduction;// 请求路径包含的字符串private static final String UrlStr = "aliPay/";@Autowiredprivate SysPayChannelServiceImpl payChannelService;@Autowiredprivate UserMemberServiceImpl memberService;@Autowiredprivate LotteryOrderServiceImpl lotteryOrderService;public void init(ServletConfig servletConfig) throws ServletException {super.init(servletConfig);SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, servletConfig.getServletContext());}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("####################请求开始####################");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");try {//⽤户同意授权后,能获取到codeString code = request.getParameter("auth_code");//⽤户同意授权if (!code.equals("")) {CommonConfig commonConfig = new CommonConfig();//具体业务String RequestURL = request.getRequestURL().toString();logger.debug("URL : " + RequestURL);String QRCodeUrl = RequestURL.substring(RequestURL.indexOf(UrlStr) + UrlStr.length());String QRCodeReqInfo = QRCodeUrl.split("&")[0];String operatorId = QRCodeUrl.split("&")[1];logger.debug("QRCodeReqInfo : " + QRCodeReqInfo +";operatorId : " + operatorId);String advancekey = commonConfig.getLotteryorder() + QRCodeReqInfo;SysPayChannel channel = payChannelService.selectByChannelType(PayTypeConstant.Alipay);MyAliPayConfig aliPayConfig = new MyAliPayConfig();aliPayConfig.setAppId(channel.getAppid());String certsrc = channel.getPayCertUrl();Properties propertiesFile = PropertiesUtils.getPropertiesFile(certsrc);if (propertiesFile != null) {aliPayConfig.setPayeeAccount(propertiesFile.getProperty("ALI_PAYEE_ACCOUNT"));aliPayConfig.setAppId(propertiesFile.getProperty("ALI_APP_ID"));aliPayConfig.setAliPayPublicKey(propertiesFile.getProperty("ALI_ALIPAY_PUBLIC_KEY"));aliPayConfig.setAppPayPublicKey(propertiesFile.getProperty("ALI_APP_PAY_PUBLIC_KEY"));aliPayConfig.setAppPrivateKey(propertiesFile.getProperty("ALI_APP_PRIVATE_KEY"));}//获取⽹页授权access_tokenAliPayOAuth2Token aliPayOAuth2Token = AliPayOAuth2Util.getOAuth2AccessToken(aliPayConfig,code);//⽹页授权接⼝访问凭证String accessToken = aliPayOAuth2Token.getAccessToken();logger.debug("accessToken=" + accessToken);//⽤户标识String aliuserid = aliPayOAuth2Token.getUserid();logger.debug("aliuserid="+aliuserid);//获取⽤户信息AliPayUserInfo userInfo = AliPayOAuth2Util.getOAuth2UserInfo(aliPayConfig,accessToken,aliuserid);logger.debug(userInfo.getNickName()+"=====⽀付宝⽀付====="+userInfo.getUserId());//添加或更新⽤户信息String userid = UserInfoService.CreateUserMember(userInfo,memberService);if (!redis.exists(advancekey)) {// 判断key是否存在logger.debug("⼆维码失效");request.setAttribute("code", ResultContant.notuserdqrcode);request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request, response);logger.debug("####################请求结束####################");return;}if (StringUtils.trimToEmpty(redis.get(advancekey)).equals("")) {logger.debug("⼆维码失效");request.setAttribute("code", ResultContant.notuserdqrcode);request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request, response);logger.debug("####################请求结束####################");return;}JSONObject jsonObject = JSONObject.parseObject(redis.get(advancekey));if (null == jsonObject) {logger.debug("⼆维码失效");request.setAttribute("code", ResultContant.notuserdqrcode);request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request, response);logger.debug("####################请求结束####################");return;}if (redis.get(advancekey + "_lock") != null && !redis.get(advancekey + "_lock").equals("")){logger.debug("⼆维码失效");request.setAttribute("code", ResultContant.notuserdqrcode);request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request, response);logger.debug("####################请求结束####################");return;}redis.setex(advancekey + "_lock", 1, "lock");String orderid = BusinessCodeUtils.getOrderNo(jsonObject.getString(SysKey.deviceSn));int money = jsonObject.getIntValue(SysKey.money);int lotterytype = jsonObject.getIntValue(SysKey.lotteryType);if (!orderid.equals("") && money != 0) {//创建订单boolean bool = OrderServcie.createorder(QRCodeReqInfo, PayTypeConstant.Alipay, aliPayConfig.getAppId(), userid, aliuserid, orderid, jsonObject, lotteryOrderService);if (bool) {//删除预订单信息redis.del(advancekey);//⼀个预订单只能创建⼀个订单String paymoney = BigDecimal.valueOf(Long.valueOf(money)).divide(new BigDecimal(100)).toString();if (!isProduction) {//测试环境paymoney = BigDecimal.valueOf(Long.valueOf(paymoney)).divide(new BigDecimal(100)).toString();//真实⾦额除100}logger.debug("是否⽣产环境:"+isProduction+";订单⾦额为:"+BigDecimal.valueOf(Long.valueOf(money)).divide(new BigDecimal(100)).toString()+";实际⽀付⾦额为:"+paymoney); //创建⽀付宝订单String responsestr = AlipayPayUtils.createOrderWapPay(domain, aliPayConfig, orderid, lotterytype==0?"即开票":"电脑票", paymoney, "");logger.debug("创建⽀付宝⽀付预订单返回数据:"+responsestr);if (!responsestr.equals("")) {response.setContentType("text/html;charset=UTF-8");response.getWriter().write(responsestr);//直接将完整的表单html输出到页⾯response.getWriter().flush();response.getWriter().close();response.getWriter().append("Served at: ").append(request.getContextPath());} else {logger.debug("创建订单失败:创建⽀付预订单失败");request.setAttribute("code", ResultContant.createordererror);request.setAttribute("message", "创建订单失败");request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request, response);}} else {logger.debug("创建订单失败:创建⽀付预订单失败");request.setAttribute("code", ResultContant.createordererror);request.setAttribute("message", "创建订单失败");request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request, response);}} else {logger.debug("创建订单失败;订单⾦额或者订单号数据有误");request.setAttribute("code", ResultContant.createordererror);request.setAttribute("message", "创建订单失败");request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request, response);}}} catch (Exception e) {e.printStackTrace();logger.debug("系统异常");request.setAttribute("code", "⼆维码失效");request.setAttribute("message", "⼆维码失效");request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request, response);}logger.debug("####################请求结束####################");}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}三、创建微信⽀付结果回调接⼝和⽀付宝⽀付接⼝回调接⼝,⽤于接收微信或者⽀付宝的⽀付结果通知;aliPayNotify ⽀付宝⽀付成功回调接⼝/*** @Title: aliPayNotify* @Description: TODO(⽀付宝⽀付成功过回调)* @author chenkun* @return 参数* @return String 返回类型* @throws*/@RequestMapping(value = "/aliPayNotify", method = RequestMethod.POST)public String aliPayNotify() {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();Map<String, String> params = convertRequestParamsToMap(request); // 将异步通知中收到的待验证所有参数都存放到map中String paramsJson = JSON.toJSONString(params);("⽀付宝⽀付回调,{" + paramsJson + "}");try {SysPayChannel channel = payChannelService.selectByChannelType(PayTypeConstant.Alipay);MyAliPayConfig aliPayConfig = new MyAliPayConfig();aliPayConfig.setAppId(channel.getAppid());String certsrc = channel.getPayCertUrl();Properties propertiesFile = PropertiesUtils.getPropertiesFile(certsrc);if (propertiesFile != null) {aliPayConfig.setPayeeAccount(propertiesFile.getProperty("ALI_PAYEE_ACCOUNT"));aliPayConfig.setAppId(propertiesFile.getProperty("ALI_APP_ID"));aliPayConfig.setAliPayPublicKey(propertiesFile.getProperty("ALI_ALIPAY_PUBLIC_KEY"));aliPayConfig.setAppPayPublicKey(propertiesFile.getProperty("ALI_APP_PAY_PUBLIC_KEY"));aliPayConfig.setAppPrivateKey(propertiesFile.getProperty("ALI_APP_PRIVATE_KEY"));}// 调⽤SDK验证签名boolean signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getAliPayPublicKey(),aliPayConfig.getCharset(), aliPayConfig.getSigntype());if (signVerified) {("⽀付宝回调签名认证成功");// 按照⽀付结果异步通知中的描述,对⽀付结果中的业务内容进⾏1\2\3\4⼆次校验,校验成功后在response中返回success,校验失败返回failure this.check(params);// 另起线程处理业务executorService.execute(new AliPayNotifyTask(params,payCallBackService));// 如果签名验证正确,⽴即返回success,后续业务另起线程单独处理// 业务处理失败,可查看⽇志进⾏补偿,跟⽀付宝已经没多⼤关系。

支付宝和微信支付流程和技术说明

支付宝和微信支付流程和技术说明

1.1微信支付1.1.1JSAPI网页支付JSAPI网页支付即前文说的公众号支付,可在微信公众号、朋友圈、聊天会话中点击页面链接,或者用微信“扫一扫”扫描页面地址二维码在微信中打开商户HTML5页面,在页面内下单完成支付。

1.1.2Native原生支付Native原生支付即前文说的扫码支付,商户根据微信支付协议格式生成的二维码,用户通过微信“扫一扫”扫描二维码后即进入付款确认界面,输入密码即完成支付。

1.1.3接入方式微信支付系统是指完成微信支付流程中涉及的API接口、后台业务处理系统、账务系统、回调通知等系统的总称。

微信支付分为公众号支付,App支付,扫码支付(包括PC 网站),刷卡支付(设备扫描用户手机)本项目主要适用扫码支付。

接通扫码支付流程:用户扫描商户展示在各种场景的二维码进行支付。

步骤1:商户根据微信支付的规则,为不同商品生成不同的二维码,展示在各种场景,用于用户扫描购买。

步骤2:用户使用微信“扫一扫”扫描二维码后,获取商品支付信息,引导用户完成支付。

步骤(3):用户确认支付,输入支付密码。

步骤(4):支付完成后会提示用户支付成功,商户后台得到支付成功的通知,然后进行发货处理。

开发步骤:商户后台系统根据微信支付规则链接生成二维码,链接中带固定参数productid(可定义为产品标识或订单号)。

用户扫码后,微信支付系统将productid和用户唯一标识(openid)回调商户后台系统(需要设置支付回调URL),商户后台系统根据productid生成支付交易,最后微信支付系统发起用户支付流程。

商户支付回调URL设置指引:进入公众平台-->微信支付-->开发配置-->扫码支付-->修改1.1.4微信服务号支付申请一、需要注册服务号,并通过认证(认证需要300元),需要准备如下材料(如下材料包含商户功能需要的材料):1. 营业执照副本扫描成电子版图片(或者提供拍照,要求看清楚)2. 组织机构代码扫描成电子版图片(或者提供拍照,要求看清楚)3. 本人手持身份证清晰照片(请看附件中图例)4. 本人身份证扫描件(正反面)5. 授权运营书(企业微信公众号认证申请信息表或个体工商户申请认证函)6. 财付通结算银行证明函7. 税务登记证(国税)8. 公共号申请信息表(公司),具体表格网站上可下载,对应自己的经营性质。

微信扫码支付java版完整demo

微信扫码支付java版完整demo

微信扫码⽀付java版完整demo ⽰例说明:微信⽀付接⼝官⽅⽂档地址:https:///wiki/doc/api/native.php?chapter=6_5本 demo 使⽤的⽀付⽅式为: 模式⼆⽂章最下⽅有可以直接运⾏的demo的百度云下载地址项⽬结构:项⽬代码:pom⽂件<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 https:///xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.zhangye</groupId><artifactId>wxpay</artifactId><version>0.0.1-SNAPSHOT</version><name>wxpay</name><packaging>jar</packaging><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.3.RELEASE</version><relativePath/><!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><commons-lang3.version>3.7</commons-lang3.version><commons-collections.version>3.2.2</commons-collections.version><com.google.zxing.version>3.3.3</com.google.zxing.version><fastjson.version>1.2.46</fastjson.version></properties><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!-- 热部署模块 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- Commons utils begin --><dependency><groupId>mons</groupId><artifactId>commons-lang3</artifactId><version>${commons-lang3.version}</version></dependency><dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId><version>${commons-collections.version}</version></dependency><!-- Commons utils end --><!-- google ⽣成⼆维码 begin--><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>${com.google.zxing.version}</version></dependency><!-- google ⽣成⼆维码 end--><!-- JSONObject JSONArray begin --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>${fastjson.version}</version></dependency><!-- JSONObject JSONArray end --></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><fork>true</fork></configuration></plugin></plugins></build></project>controller--WxPayControllerpackage com.zhangye.wxpay.modules.controller;import com.alibaba.fastjson.JSONObject;import mon.wx.WxConfig; import mon.wx.WxConstants; import mon.wx.WxUtil; import com.zhangye.wxpay.modules.model.Order;import com.zhangye.wxpay.modules.service.WxMenuService; import ng3.StringUtils;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;/*** @author zhangye* @version 1.0* @description 微信扫码⽀付接⼝* @date 2019/12/19* <p>* 微信⽀付接⼝官⽅⽂档地址:https:///wiki/doc/api/native.php?chapter=6_5 * 本 demo 使⽤的⽀付⽅式为: 模式⼆* <p>* 微信扫码⽀付流程说明:* 1.需要商户⽣成订单* 2.商户调⽤微信统⼀下单接⼝获取⼆维码链接 code_url (请求参数请见官⽅⽂档)* 请求参数中的 notify_url 为⽤户⽀付成功后, 微信服务端回调商户的接⼝地址* 3.商户根据 code_url ⽣成⼆维码* 4.⽤户使⽤微信扫码进⾏⽀付* 5.⽀付成功后, 微信服务端会调⽤ notify_url 通知商户⽀付结果* 6.商户接到通知后, 执⾏业务操作(修改订单状态等)并告知微信服务端接收通知成功* <p>* 查询微信⽀付订单、关闭微信⽀付订单流程较为简单,请⾃⾏查阅官⽅⽂档*/@Controllerpublic class WxPayController {@Autowiredprivate WxMenuService wxMenuService;/*** ⼆维码⾸页测试⽤*/@RequestMapping(value = {"/"}, method = RequestMethod.GET)public String wxPayList(Model model) {//商户订单号model.addAttribute("outTradeNo", WxUtil.mchOrderNo());return "/wxPayList";}/*** 获取订单流⽔号测试⽤*/@RequestMapping(value = {"/wxPay/outTradeNo"})@ResponseBodypublic String getOutTradeNo(Model model) {//商户订单号return WxUtil.mchOrderNo();}/*** 默认 signType 为 md5*/final private String signType = WxConstants.SING_MD5;/*** 微信⽀付统⼀下单-⽣成⼆维码* 1.请求微信预下单接⼝* 2.根据预下单返回的 code_url ⽣成⼆维码* 3.将⼆维码 write 到前台页⾯*/@RequestMapping(value = {"/wxPay/payUrl"})public void payUrl(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "totalFee") int totalFee,@RequestParam(value = "outTradeNo") String outTradeNo,@RequestParam(value = "productId") String productId) throws Exception { //模拟测试订单信息Order order = new Order();order.setClintIp("123.12.12.123");order.setOrderNo(outTradeNo);order.setProductId(productId);order.setSubject("ESM365充值卡");order.setTotalFee(totalFee);//获取⼆维码链接String codeUrl = wxMenuService.wxPayUrl(order, signType);if (!StringUtils.isNotBlank(codeUrl)) {System.out.println("----⽣成⼆维码失败----");WxConfig.setPayMap(outTradeNo, "CODE_URL_ERROR");} else {//根据链接⽣成⼆维码WxUtil.writerPayImage(response, codeUrl);}}/*** 微信⽀付统⼀下单-通知链接* 1.⽤户⽀付成功后* 2.微信回调该⽅法* 3.商户最终通知微信已经收到结果*///商户订单号String outTradeNo = null;String xmlContent = "<xml>" +"<return_code><![CDATA[FAIL]]></return_code>" +"<return_msg><![CDATA[签名失败]]></return_msg>" +"</xml>";try {String requestXml = WxUtil.getStreamString(request.getInputStream());System.out.println("requestXml : " + requestXml);Map<String, String> map = WxUtil.xmlToMap(requestXml);String returnCode = map.get(WxConstants.RETURN_CODE);//校验⼀下,判断是否已经⽀付成功if (StringUtils.isNotBlank(returnCode) && StringUtils.equals(returnCode, "SUCCESS") && WxUtil.isSignatureValid(map, WxConfig.key, signType)) { //商户订单号outTradeNo = map.get("out_trade_no");System.out.println("outTradeNo : " + outTradeNo);//微信⽀付订单号String transactionId = map.get("transaction_id");System.out.println("transactionId : " + transactionId);//⽀付完成时间SimpleDateFormat payFormat = new SimpleDateFormat("yyyyMMddHHmmss");Date payDate = payFormat.parse(map.get("time_end"));SimpleDateFormat systemFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");System.out.println("⽀付时间:" + systemFormat.format(payDate));//临时缓存WxConfig.setPayMap(outTradeNo, "SUCCESS");//根据⽀付结果修改数据库订单状态//其他操作//......//给微信的应答 xml, 通过 response 回写xmlContent = "<xml>" +"<return_code><![CDATA[SUCCESS]]></return_code>" +"<return_msg><![CDATA[OK]]></return_msg>" +"</xml>";}} catch (Exception e) {e.printStackTrace();}WxUtil.responsePrint(response, xmlContent);}/*** 前台页⾯定时器查询是否已⽀付* 1.前台页⾯轮询* 2.查询订单⽀付状态*/@RequestMapping(value = {"/wxPay/payStatus"})@ResponseBodypublic String payStatus(@RequestParam(value = "outTradeNo") String outTradeNo) {JSONObject responseObject = new JSONObject();//从临时缓存中取String outTradeNoValue = WxConfig.getPayMap(outTradeNo);String status = "200";//判断是否已经⽀付成功if (StringUtils.isNotBlank(outTradeNoValue)) {if (StringUtils.equals(outTradeNoValue, "SUCCESS")) {status = "0";} else if (StringUtils.equals(outTradeNoValue, "CODE_URL_ERROR")) {//⽣成⼆维码失败status = "1";}} else {//如果临时缓存中没有去数据库读取//......}responseObject.put("status", status);return responseObject.toJSONString();}/*** 微信⽀付订单查询* 1.如果由于⽹络通信问题导致微信没有通知到商户⽀付结果* 2.商户主动去查询⽀付结果⽽后执⾏其他业务操作*/@RequestMapping(value = {"/wxPay/orderQuery"})@ResponseBodypublic String orderQuery(@RequestParam(value = "orderNo") String orderNo) throws Exception {String result = wxMenuService.wxOrderQuery(orderNo, signType);return result;}/*** 关闭微信⽀付订单* 1.商户订单⽀付失败需要⽣成新单号重新发起⽀付,要对原订单号调⽤关单,避免重复⽀付* 2.系统下单后,⽤户⽀付超时,系统退出不再受理,避免⽤户继续,请调⽤关单接⼝@ResponseBodypublic String closeOrder(@RequestParam(value = "orderNo") String orderNo) throws Exception { String result = wxMenuService.wxCloseOrder(orderNo, signType);return result;}//申请退款//查询退款}service--WxMenuServicepackage com.zhangye.wxpay.modules.service;import com.zhangye.wxpay.modules.model.Order;/*** @author zhangye* @version 1.0* @description 微信⽀付接⼝类* @date 2019/12/19*/public interface WxMenuService {/*** ⽣成⽀付⼆维码URL** @param order 订单类* @param signType 签名类型* @throws Exception*/String wxPayUrl(Order order, String signType) throws Exception;/*** 查询微信订单** @param orderNo 订单号* @param signType 签名类型* @return*/String wxOrderQuery(String orderNo, String signType) throws Exception;/*** 关闭微信⽀付订单** @param orderNo 订单号* @param signType 签名类型* @return*/String wxCloseOrder(String orderNo, String signType) throws Exception;}service--impl--WxMenuServiceImplpackage com.zhangye.wxpay.modules.service.impl;import mon.http.HttpsClient;import mon.wx.WxConfig;import mon.wx.WxConstants;import mon.wx.WxUtil;import com.zhangye.wxpay.modules.model.Order;import com.zhangye.wxpay.modules.service.WxMenuService;import org.springframework.stereotype.Service;import java.util.HashMap;import java.util.Map;/*** @author zhangye* @version 1.0* @description 微信⽀付实现类* @date 2019/12/19*/@Service("wxMenuService")public class WxMenuServiceImpl implements WxMenuService {@Overridepublic String wxPayUrl(Order order, String signType) throws Exception {HashMap<String, String> data = new HashMap<String, String>();//公众账号IDdata.put("appid", WxConfig.appID);//商户号data.put("mch_id", WxConfig.mchID);//随机字符串data.put("nonce_str", WxUtil.getNonceStr());//商品描述data.put("body", order.getSubject());//商户订单号data.put("fee_type", "CNY");//标价⾦额data.put("total_fee", String.valueOf(order.getTotalFee()));//⽤户的IPdata.put("spbill_create_ip", order.getClintIp());//通知地址data.put("notify_url", WxConfig.unifiedorderNotifyUrl);//交易类型data.put("trade_type", "NATIVE");//签名类型data.put("sign_type", signType);//商品iddata.put("product_id", order.getProductId());//签名签名中加⼊keydata.put("sign", WxUtil.getSignature(data, WxConfig.key, signType));String requestXML = WxUtil.mapToXml(data);String responseString = HttpsClient.httpsRequestReturnString(WxConstants.PAY_UNIFIEDORDER, HttpsClient.METHOD_POST, requestXML);//解析返回的xmlMap<String, String> resultMap = WxUtil.processResponseXml(responseString, signType);if (resultMap.get(WxConstants.RETURN_CODE).equals("SUCCESS")) {return resultMap.get("code_url");}return null;}@Overridepublic String wxOrderQuery(String orderNo, String signType) throws Exception {HashMap<String, String> data = new HashMap<String, String>();//公众账号IDdata.put("appid", WxConfig.appID);//商户号data.put("mch_id", WxConfig.mchID);//随机字符串data.put("nonce_str", WxUtil.getNonceStr());//商户订单号data.put("out_trade_no", orderNo);//签名类型data.put("sign_type", signType);//签名签名中加⼊keydata.put("sign", WxUtil.getSignature(data, WxConfig.key, signType));String requestXML = WxUtil.mapToXml(data);String responseString = HttpsClient.httpsRequestReturnString(WxConstants.PAY_ORDERQUERY, HttpsClient.METHOD_POST, requestXML);//解析返回的xmlMap<String, String> resultMap = WxUtil.processResponseXml(responseString, signType);if (resultMap.get(WxConstants.RETURN_CODE).equals("SUCCESS")) {/*** 订单⽀付状态* SUCCESS—⽀付成功* REFUND—转⼊退款* NOTPAY—未⽀付* CLOSED—已关闭* REVOKED—已撤销(刷卡⽀付)* USERPAYING--⽤户⽀付中* PAYERROR--⽀付失败(其他原因,如银⾏返回失败)*/return resultMap.get("trade_state");}return null;}@Overridepublic String wxCloseOrder(String orderNo, String signType) throws Exception {HashMap<String, String> data = new HashMap<String, String>();//公众账号IDdata.put("appid", WxConfig.appID);//商户号data.put("mch_id", WxConfig.mchID);//随机字符串data.put("nonce_str", WxUtil.getNonceStr());//商户订单号data.put("out_trade_no", orderNo);//签名类型data.put("sign_type", signType);//签名签名中加⼊keydata.put("sign", WxUtil.getSignature(data, WxConfig.key, signType));String requestXML = WxUtil.mapToXml(data);String responseString = HttpsClient.httpsRequestReturnString(WxConstants.PAY_CLOSEORDER, HttpsClient.METHOD_POST, requestXML);//解析返回的xmlMap<String, String> resultMap = WxUtil.processResponseXml(responseString, signType);if (resultMap.get(WxConstants.RETURN_CODE).equals("SUCCESS")) {/*** 关闭订单状态* SUCCESS—关闭成功* FAIL—关闭失败*/return resultMap.get("result_code");}return null;}common--http--HttpsClientpackage mon.http;import com.alibaba.fastjson.JSONObject;import mon.wx.WxConfig;import mon.wx.WxConstants;import mon.wx.WxUtil;import ng3.StringUtils;import .ssl.HttpsURLConnection;import .ssl.SSLContext;import .ssl.SSLSocketFactory;import .ssl.TrustManager;import java.io.OutputStream;import .URL;/*** @author zhangye* @version 1.0* @description HttpsClient类* @date 2019/12/19*/public class HttpsClient {/*** GET请求⽅式*/public static final String METHOD_GET = "GET";/*** POST请求⽅式*/public static final String METHOD_POST = "POST";/*** 连接超时时间*/private static Integer CONNECTION_TIMEOUT = WxConfig.connectionTimeout;/*** 请求超时时间*/private static Integer READ_TIMEOUT = WxConfig.readTimeout;/*** 发起https请求** @param requestUrl 请求地址* @param requestMethod 请求⽅式(Get或者post)* @param postData 提交数据* @return JSONObject*/public static JSONObject httpsRequestReturnJSONObject(String requestUrl, String requestMethod, String postData) throws Exception {JSONObject jsonObject = JSONObject.parseObject(HttpsClient.httpsRequestReturnString(requestUrl, requestMethod, postData));System.out.println("jsonObjectDate: " + jsonObject);return jsonObject;}/*** 发起https请求** @param requestUrl 请求地址* @param requestMethod 请求⽅式(Get或者post)* @param postData 提交数据* @return String*/public static String httpsRequestReturnString(String requestUrl, String requestMethod, String postData) throws Exception {String response;HttpsURLConnection httpsUrlConnection = null;try {//创建https请求证书TrustManager[] tm = {new MyX509TrustManager()};//创建SSLContext管理器对像,使⽤我们指定的信任管理器初始化SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");sslContext.init(null, tm, new java.security.SecureRandom());SSLSocketFactory ssf = sslContext.getSocketFactory();// 创建URL对象URL url = new URL(requestUrl);// 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象httpsUrlConnection = (HttpsURLConnection) url.openConnection();//设置ssl证书httpsUrlConnection.setSSLSocketFactory(ssf);//设置header信息httpsUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置User-Agent信息httpsUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");//设置可接受信息httpsUrlConnection.setDoInput(true);//不使⽤缓存httpsUrlConnection.setUseCaches(false);//设置请求⽅式(GET/POST)httpsUrlConnection.setRequestMethod(requestMethod);//设置连接超时时间if (CONNECTION_TIMEOUT > 0) {httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT);} else {//默认10秒超时httpsUrlConnection.setConnectTimeout(10000);}//设置请求超时if (READ_TIMEOUT > 0) {httpsUrlConnection.setReadTimeout(READ_TIMEOUT);} else {//默认10秒超时httpsUrlConnection.setReadTimeout(10000);}//设置编码httpsUrlConnection.setRequestProperty("Charsert", WxConstants.DEFAULT_CHARSET);//判断是否需要提交数据if (StringUtils.equals(requestMethod, HttpsClient.METHOD_POST) && StringUtils.isNotBlank(postData)) { //讲参数转换为字节提交byte[] bytes = postData.getBytes(WxConstants.DEFAULT_CHARSET);//设置头信息httpsUrlConnection.setRequestProperty("Content-Length", Integer.toString(bytes.length));//开始连接httpsUrlConnection.connect();//防⽌中⽂乱码OutputStream outputStream = httpsUrlConnection.getOutputStream();outputStream.write(postData.getBytes(WxConstants.DEFAULT_CHARSET));outputStream.flush();outputStream.close();} else {//开始连接httpsUrlConnection.connect();}response = WxUtil.getStreamString(httpsUrlConnection.getInputStream());} catch (Exception e) {throw new Exception();} finally {if (httpsUrlConnection != null) {// 关闭连接httpsUrlConnection.disconnect();}}return response;}}common--http--MyX509TrustManagerpackage mon.http;import .ssl.X509TrustManager;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;/*** @author zhangye* @version 1.0* @description X509TrustManager⽤于实现SSL证书的安全校验* @date 2019/12/19*/public class MyX509TrustManager implements X509TrustManager {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}}common--util--SHA1package mon.util;import java.security.MessageDigest;/*** @version 1.0* @description 微信SHA1算法* @date 2019/12/19*/public final class SHA1 {private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; /*** 将字节并格式化** @param bytes 原始字节* @return格式化字节*/private static String getFormattedText(byte[] bytes) {int len = bytes.length;StringBuilder buf = new StringBuilder(len * 2);// 把密⽂转换成⼗六进制的字符串形式for (int j = 0; j < len; j++) {buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);buf.append(HEX_DIGITS[bytes[j] & 0x0f]);}return buf.toString();}public static String encode(String str) {if (str == null) {return null;}try {MessageDigest messageDigest = MessageDigest.getInstance("SHA1");messageDigest.update(str.getBytes());return getFormattedText(messageDigest.digest());} catch (Exception e) {throw new RuntimeException(e);}}}common--wx--WxConfigpackage mon.wx;import org.springframework.beans.factory.annotation.Value;import ponent;import java.util.HashMap;/*** @author zhangye* @version 1.0* @description 微信公众号开发配置类* @date 2019/12/19*/@Componentpublic class WxConfig {/*** 开发者ID*/public static String appID;@Value("${wx.appID}")public void setAppID(String appID) {this.appID = appID;}/*** 开发者密码*/public static String appSecret;@Value("${wx.appSecret}")public void setAppSecret(String appSecret) {this.appSecret = appSecret;}/*** 商户号*/public static String mchID;@Value("${wx.mchID}")public void setMchID(String mchID) {this.mchID = mchID;}/*** API密钥*/public static String key;public void setKey(String key) {this.key = key;}/*** 统⼀下单-通知链接*/public static String unifiedorderNotifyUrl;@Value("${wx.unifiedorder.notifyUrl}")public void setUnifiedorderNotifyUrl(String unifiedorderNotifyUrl) {this.unifiedorderNotifyUrl = unifiedorderNotifyUrl;}/*** 连接超时时间*/public static Integer connectionTimeout;@Value("${https.connectionTimeout}")public void setConnectionTimeout(Integer connectionTimeout) {this.connectionTimeout = connectionTimeout;}/*** 连接超时时间*/public static Integer readTimeout;@Value("${https.readTimeout}")public void setReadTimeout(Integer readTimeout) {this.readTimeout = readTimeout;}//⽀付map缓存处理private static HashMap<String,String> payMap = new HashMap<String,String>();public static String getPayMap(String key) {return payMap.get(key);}public static void setPayMap(String key,String value) {payMap.put(key,value);}}common--wx--WxConstantspackage mon.wx;/*** @author zhangye* @version 1.0* @description 微信公众号常量类* @date 2019/12/19*/public class WxConstants {/*** 默认编码*/public static final String DEFAULT_CHARSET = "UTF-8";/*** 统⼀下单-扫描⽀付*/public static String PAY_UNIFIEDORDER = "https:///pay/unifiedorder"; /*** 统⼀下单-查询订单*/public static String PAY_ORDERQUERY = "https:///pay/orderquery"; /*** 统⼀下单-关闭订单*/public static String PAY_CLOSEORDER = "https:///pay/closeorder"; /*** 请求成功返回码*/public final static String ERRCODE_OK_CODE = "0";/*** 错误的返回码的Key*/public final static String ERRCODE = "errcode";/*** 返回状态码*/public final static String RETURN_CODE = "return_code";/**public final static String ACCESS_TOKEN = "access_token";/*** 签名类型 MD5*/public final static String SING_MD5 = "MD5";/*** 签名类型 HMAC-SHA256*/public final static String SING_HMACSHA256 = "HMAC-SHA256";}common--wx--WxUtilpackage mon.wx;import com.google.zxing.BarcodeFormat;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatWriter;import com.google.zxing.client.j2se.MatrixToImageWriter;import mon.BitMatrix;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import mon.util.SHA1;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import java.io.*;import java.security.MessageDigest;import java.text.SimpleDateFormat;import java.util.*;/*** @author zhangye* @version 1.0* @description 微信公众号接⼝⼯具类* 在微信提供的 skk 中的 WXPayUtil 基础上根据⾃⼰的需求做出了⼀些修改* 微信 sdk 下载地址: https:///wiki/doc/api/native.php?chapter=11_1* @date 2019/12/19*/public class WxUtil {/*** 加密/校验流程如下:* 1. 将token、timestamp、nonce 三个参数进⾏字典序排序* 2. 将三个参数字符串拼接成⼀个字符串进⾏ sha1 加密* 3. 开发者获得加密后的字符串可与 signature 对⽐,标识该请求来源于微信** @param token Token验证密钥* @param signature 微信加密签名,signature 结合了开发者填写的 token 参数和请求中的 timestamp 参数,nonce 参数 * @param timestamp 时间戳* @param nonce 随机数* @return验证成功返回:true, 失败返回:false*/public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {List<String> params = new ArrayList<String>();params.add(token);params.add(timestamp);params.add(nonce);//1. 将token、timestamp、nonce三个参数进⾏字典序排序Collections.sort(params, new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {return pareTo(o2);}});//2. 将三个参数字符串拼接成⼀个字符串进⾏sha1加密String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));//3. 开发者获得加密后的字符串可与signature对⽐,标识该请求来源于微信return temp.equals(signature);}/*** 输⼊流转化为字符串** @param inputStream 流* @return String 字符串public static String getStreamString(InputStream inputStream) throws Exception {StringBuffer buffer = new StringBuffer();InputStreamReader inputStreamReader = null;BufferedReader bufferedReader = null;try {inputStreamReader = new InputStreamReader(inputStream, WxConstants.DEFAULT_CHARSET);bufferedReader = new BufferedReader(inputStreamReader);String line;while ((line = bufferedReader.readLine()) != null) {buffer.append(line);}} catch (Exception e) {throw new Exception();} finally {if (bufferedReader != null) {bufferedReader.close();}if (inputStreamReader != null) {inputStreamReader.close();}if (inputStream != null) {inputStream.close();}}return buffer.toString();}/*** 获取随机字符串 Nonce Str** @return String 随机字符串*/public static String getNonceStr() {return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);}/*** ⽣成签名. 注意,若含有sign_type字段,必须和signType参数保持⼀致。

[DEMO]支付宝网页支付及微信网页扫码支付

[DEMO]支付宝网页支付及微信网页扫码支付

[DEMO] 支付宝网页支付及微信网页扫码支付DEMO 包含支付宝网页支付以及微信扫码支付功能,相对于手机端支付,完善支付场景,使PC 端与移动端都能实现支付需要。

摘要:DEMO 已经将支付宝及微信支付需要的配置信息独立化,导入,配置,即可使用。

对于各平台应用前置配置要求,接口各参数意义及用途,请参阅:支付宝网页支付官方文档微信扫码支付(模式二)官方文档XPZ 下载:Demo_PCPayment_20180102-114.1.zip (1.04 MB, 下载次数: 1)Note:修复支付宝支付成功页面PaySuccess验签参数SDT 错误XPZ 下载:Demo_PCPaymen-t114.2.zip (1.04 MB, 下载次数: 1)另:此xpz 中使用了支付宝服务端sdk,现只实现了.Net 环境的封装,java 环境之后补充。

说明:导入xpz,配置数据库连接信息,编译运行。

导入module 结构如下:打开访问pcpayment.main.aspx页面点击“加载配置”按钮可以加载默认配置按照文档说明配置各参数,点击“保存配置”按钮保存修改页面下方是用户信息及各用户的支付记录,默认初始化了三个用户用于测试点击“支付宝支付”按钮,进入支付宝支付页面默认填入了商品信息及金额,点击页面下方确认支付”按钮进行支付正常情况下会返回一个form 表单的字符串,及支付宝返回的订单信息点击“访问上面的返回form 支付”按钮,触发表单中自动提交事件,打开支付宝网页支付页面完成支付后,将跳转到支付成功页面返回main 页面查看用户支付记录可以查看到支付时间,同步返回及异步通知的信息。

可以看到,支付状态一栏中显示了接收到同步及异步信息的先后顺序,且用户关闭支付宝页面后将无法跳转到成功提示页面,及没有同步返回消息,因此,务必按照官方推荐,在异步通知中处理支付成功逻辑。

点击“微信支付 ”按钮,进入微信扫码支付页面默认填入了订单信息及金额,点击 “确认支付 ”按钮调用微信统一下单 API ,获取 返回参数。

vue项目中的支付功能实现(微信支付和支付宝支付)

vue项目中的支付功能实现(微信支付和支付宝支付)

vue项⽬中的⽀付功能实现(微信⽀付和⽀付宝⽀付)⽬录项⽬中常见的⽀付⽅式⽀付宝⽀付微信⽀付项⽬中常见的⽀付⽅式⽀付宝⽀付微信⽀付余额⽀付(也需要⽀付宝或微信充值)注意:本⽂仅从前端⾓度展开讲解⽀付宝⽀付项⽬难点:页⾯是h5⽹页,⽤⽀付宝⽀付必须得到⽀付宝授权,调⽤⽀付宝的api。

(如何授权请参照:)⽀付宝⽀付的⼀般过程是:调⽤订单接⼝,获得订单号,⽀付⾦额等。

传递订单号,⾦额⾄预⽀付接⼝后台会返回来⼀个form,然后提交form⾃动跳转到⽀付宝⽀付页⾯⽀付过程:下图为为接⼝⽂档,⽀付接⼝当我们选中⽀付宝,radio=1;当我们点击⽀付按钮,pay()⽅法执⾏此时我们调⽤后端⽀付接⼝,传⼊接⼝⽂档要求字段,订单号,⾦额等。

后台回传给我们⼀个{code:201,data:""};此时我们把form注⼊到我们页⾯中,让form表单提交,跳转到⽀付宝页⾯topay(){switch(this.radio){case '3':this.yuer();break;case '1':this.zhifubao();case '0':this.getWechatCode();}},zhifubao(){payByZhifubao({OutTradeNo:'Oct20200909095646265303127',//商户订单号,商户⽹站订单系统中唯⼀订单号,必填。

需要保证商户端唯⼀。

Subject: "⼿机⽹站⽀付测试",//主题ProductCode: "QUICK_WAP_WAY",body: "⼿机⽹站⽀付描述信息",//商品描述,可空TotalAmount: 20 //付款⾦额,必填 }).then(res=>{console.log(res);if (res.code === 201) {//将数据存到vuex中// this.$store.dispatch('addAliFrom', res.data.data)this.html = res.data;var form = res.data;const div = document.createElement("div");div.innerHTML = form; //此处form就是后台返回接收到的数据document.body.appendChild(div);document.forms[0].submit();//return this.$router.push('/aliPay')} else {return alert(res.data.msg);}})},微信⽀付步骤:微信⽀付后台程序员会给你返⼀个地址,⾸先我们需要安装qrcodejs2将地址转换成⼆维码,需要先npm install qrcodejs2然后需要⼀个div来存放这个微信⼆维码,宽⾼样式各位⾃⼰可以去css⾥写,我在这⾥还加了⼀个loading,有需要的也可以⾃⼰加<div id="wechatcode" v-loading="loading"element-loading-text="拼命加载中"element-loading-spinner="el-icon-loading"element-loading-background="rgba(0, 0, 0, 0.8)"></div>导⼊模块import QRCode from 'qrcodejs2' // 引⼊qrcode下⾯是接⼝数据获取然后操作⼆维码getWechatCode() {Models.getModel("wechatpay").get({orderId:this.orderId}).then(res => {if(res.data.code == 200){this.wechatPayUrl = res.data.resultDataif(!this.flag){//重点是这⾥,其余的是为了我的切换业务逻辑和接⼝let wechatcode = new QRCode('wechatcode', {width: 200,height: 200,text: this.wechatPayUrl, // ⼆维码地址colorDark: "#000",colorLight: "#fff",})}this.flag = truethis.loading = falsethis.isWechatCodeShow = true}})},在微信扫描⽀付完之后,后台⼈员可以拿到⽀付成功结果,返给前台⼈员,那么前端⼈员只能不断去调接⼝查询是否已⽀付,在这⾥我们可以⽤⽣命周期来做轮询,在跳出之后需要销毁mounted() {this.getWechatCode()//实现轮询this.interval = window.setInterval(() => {setTimeout(this.getOrderStatus(), 0);}, 3000);},beforeDestroy() {//清除轮询clearInterval(this.interval)this.interval = null},这⾥的`getOrderStatus()⽅法是为了查询后台⽀付状态的,如果成功跳转到⽀付页⾯,做个If else判断即可到此这篇关于vue项⽬中的⽀付功能实现(微信⽀付和⽀付宝⽀付)的⽂章就介绍到这了,更多相关vue项⽬⽀付内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

[DEMO] 支付宝网页支付及微信网页扫码支付
DEMO包含支付宝网页支付以及微信扫码支付功能,相对于手机端支付,完善支付场景,使PC端与移动端都能实现支付需要。

摘要:
DEMO已经将支付宝及微信支付需要的配置信息独立化,导入,配置,即可使用。

对于各平台应用前置配置要求,接口各参数意义及用途,请参阅:
支付宝网页支付官方文档微信扫码支付(模式二)官方文档
XPZ下载:
Demo_PCPayment_20180102-114.1.zip(1.04 MB, 下载次数: 1) Note:修复支付宝支付成功页面PaySuccess验签参数SDT错误
XPZ下载:
Demo_PCPayment-114.2.zip(1.04 MB, 下载次数: 1)
另:此xpz中使用了支付宝服务端sdk,现只实现了.Net环境的封装,java 环境之后补充。

说明:
导入xpz,配置数据库连接信息,编译运行。

导入module结构如下:
打开访问pcpayment.main.aspx页面
点击“加载配置”按钮可以加载默认配置
按照文档说明配置各参数,点击“保存配置”按钮保存修改
页面下方是用户信息及各用户的支付记录,默认初始化了三个用户用于测试
点击“支付宝支付”按钮,进入支付宝支付页面
默认填入了商品信息及金额,点击页面下方“确认支付”按钮进行支付
正常情况下会返回一个form表单的字符串,及支付宝返回的订单信息
点击“访问上面的返回form支付”按钮,触发表单中自动提交事件,打开支付宝网页支付页面
完成支付后,将跳转到支付成功页面
返回main页面查看用户支付记录
可以查看到支付时间,同步返回及异步通知的信息。

可以看到,支付状态一栏中显示了接收到同步及异步信息的先后顺序,且用户关闭支付宝页面后将无法跳转到成功提示页面,及没有同步返回消息,因此,务必按照官方推荐,在异步通知中处理支付成功逻辑。

点击“微信支付”按钮,进入微信扫码支付页面
默认填入了订单信息及金额,点击“确认支付”按钮调用微信统一下单API,获取返回参数。

注意微信的金额单位是“分”,与支付宝“元”为单位不同。

且此参数不支持小数点,只能是整数,及1为最小金额,0.01元。

正常情况下可以获取到微信支付url,点击“将支付url转为二维码进行扫码支付”
按钮,获取二维码图片以进行扫码支付
支付完成后返回main页面查看用户支付记录
可以看到微信没有同步返回参数,依赖于异步通知,业务逻辑同样在异步通知时处理。

相关文档
最新文档