uniapp写支付的操作

支付的时候一般需要几个参数:

  1. ‘timeStamp’: 时间戳,
  2. ‘nonceStr’: 随机字符串,不超过32位
  3. ‘package’: 下单后接口返回的prepauid
  4. ‘signType’: 签名的算法
  5. ‘paySign’: 后端会给前端一个签名
  6. sign: data.sign // 根据签名算法生成签名
<template><view><scroll-view scroll-y><view class="block__title">报修信息</view><view class="cu-list menu"><view class="cu-item"><view class="content"><text class="text-grey">工单号</text></view><view class="action"><text class="text-grey text-sm">{{repairId}}</text></view></view><view class="cu-item"><view class="content"><text class="text-grey">报修类型</text></view><view class="action"><text class="text-grey text-sm">{{repairTypeName}}</text></view></view><view class="cu-item"><view class="content"><text class="text-grey">报修位置</text></view><view class="action"><text class="text-grey text-sm">{{repairObjName}}</text></view></view><view class="cu-item"><view class="content"><text class="text-grey">报修人</text></view><view class="action"><text class="text-grey text-sm">{{repairName}}</text></view></view><view class="cu-item"><view class="content"><text class="text-grey">报修内容</text></view><view class="action"><text class="text-grey text-sm">{{remark}}</text></view></view></view><view class="block__title">费用信息</view><view class="cu-list menu fee-last"><view class="cu-item"><view class="content"><text class="text-grey">费用编号</text></view><view class="action"><text class="text-grey text-sm">{{feeInfo.feeId }}</text></view></view><view class="cu-item"><view class="content"><text class="text-grey">金额</text></view><view class="action"><text class="text-grey text-sm">{{feeInfo.amount + '元' }}</text></view></view></view></scroll-view><view class=" bg-white  border flex justify-end" style="position: fixed;width: 100%;bottom: 0;"><view class="action text-orange margin-right line-height">合计:{{feeInfo.amount}}</view><view class="btn-group"><!-- #ifdef H5 || MP-WEIXIN --><button class="cu-btn bg-red shadow-blur lgplus sharp" @click="onPayFee()">提交订单</button><!-- #endif --><!-- #ifdef APP-PLUS --><button class="cu-btn bg-red shadow-blur lgplus sharp" @click="_payWxApp()">提交订单</button><!-- #endif --></view></view></view></view>
</template><script>import {date2String} from '../../lib/java110/utils/DateUtil.js'import context from '../../lib/java110/Java110Context.js';const constant = context.constant;const util = context.util;// #ifdef H5const WexinPayFactory = require('../../factory/WexinPayFactory.js');// #endifexport default {data() {return {communityId: '',communityName: '',repairId:'',appId: '',repairInfo:{},feeInfo:{},userId:'',payerObjId: '',payerObjType: '3333',endTime: '',repairTypeName: '',repairObjName: '',repairName: '',remark: '',};},/*** 生命周期函数--监听页面加载*/onLoad: function(options) {context.onLoad(options);// #ifdef MP-WEIXINlet accountInfo = uni.getAccountInfoSync();this.appId = accountInfo.miniProgram.appId;// #endif// #ifdef H5this.appId = uni.getStorageSync(constant.mapping.W_APP_ID)// #endifthis.communityId = options.communityId;this.repairId = options.repairId;this.userId = options.userId;this.payerObjId = options.repairObjId;this.endTime = date2String(new Date(options.appointmentTime.replace(/-/g, "/")));this.repairTypeName = options.repairTypeName;this.repairObjName = options.repairObjName;this.repairName = options.repairName;this.remark = options.contextthis._loadRepair();this._listFee();},methods: {/*** 加载我的报修* */_listFee: function() {let that = this;let _url = '';_url = constant.url.listFeeByAttr;let _paramIn = {"communityId": that.communityId,"page": 1,"row": 1,"specCd": '390001',"value": that.repairId};context.request({url: _url,header: context.getHeaders(),method: "GET",data: _paramIn,success: function(res) {let _json = res.data;if (_json.code == 0) {that.feeInfo = _json.data[0];return;}wx.showToast({title: "查询费用失败",icon: 'none',duration: 2000});},fail: function(e) {wx.showToast({title: "服务器异常了",icon: 'none',duration: 2000})}})},_loadRepair: function() {let that = this;let _url = '';_url = constant.url.listStaffFinishRepairs;let _paramIn = {"communityId": that.communityId,"page": 1,"row": 1,"userId": that.userId,"repairId": that.repairId};context.request({url: _url,header: context.getHeaders(),method: "GET",data: _paramIn,success: function(res) {let _json = res.data;if (_json.code == 0) {that.repairInfo = _json.data[0];return;}wx.showToast({title: "查询报修单失败",icon: 'none',duration: 2000});},fail: function(e) {wx.showToast({title: "服务器异常了",icon: 'none',duration: 2000})}})},_payWxApp: function(_data) {wx.showLoading({title: '支付中'});let _tradeType = 'APP';let _objData = {cycles: 1,communityId: this.communityId,feeId: this.feeInfo.feeId,feeName: '报修费',receivedAmount: this.feeInfo.feePrice,tradeType: _tradeType,appId: this.appId};context.request({url: constant.url.preOrder,header: context.getHeaders(),method: "POST",data: _objData,//动态数据success: function(res) {if (res.statusCode == 200 && res.data.code == '0') {let data = res.data; //成功情况下跳转let obj = {appid: data.appId,noncestr: data.nonceStr,package: 'Sign=WXPay', // 固定值,以微信支付文档为主partnerid: data.partnerid,prepayid: data.prepayid,timestamp: data.timeStamp,sign: data.sign // 根据签名算法生成签名}// 第二种写法,传对象字符串let orderInfo = JSON.stringify(obj)uni.requestPayment({provider: 'wxpay',orderInfo: orderInfo, //微信、支付宝订单数据success: function(res) {uni.showToast({title: "支付成功",duration: 2000});uni.navigateBack({});},fail: function(err) {console.log('fail:' + JSON.stringify(err));}});wx.hideLoading();return;}wx.hideLoading();wx.showToast({title: "缴费失败",icon: 'none',duration: 2000});},fail: function(e) {wx.hideLoading();wx.showToast({title: "服务器异常了",icon: 'none',duration: 2000});}});},onPayFee: function() {wx.showLoading({title: '支付中'});let _tradeType = 'JSAPI';let _objData = {cycles: '1',communityId: this.communityId,feeId: this.feeInfo.feeId,feeName: '报修费',receivedAmount: this.feeInfo.feePrice,tradeType: _tradeType,appId: this.appId,endTime: this.endTime,payerObjId: this.payerObjId,payerObjType: this.payerObjType};context.request({url: constant.url.preOrder,header: context.getHeaders(),method: "POST",data: _objData,//动态数据success: function(res) {if (res.statusCode == 200 && res.data.code == '0') {let data = res.data; //成功情况下跳转// #ifdef MP-WEIXINuni.requestPayment({'timeStamp': data.timeStamp,'nonceStr': data.nonceStr,'package': data.package,'signType': data.signType,'paySign': data.sign,'success': function(res) {uni.showToast({title: "支付成功",duration: 2000});uni.navigateBack({});},'fail': function(res) {console.log('fail:' + JSON.stringify(res));}});// #endif// #ifdef H5WexinPayFactory.wexinPay(data,function(){uni.showToast({title: "支付成功",duration: 2000});uni.navigateBack({});});// #endifwx.hideLoading();return;}wx.hideLoading();wx.showToast({title: "缴费失败",icon: 'none',duration: 2000});},fail: function(e) {wx.hideLoading();wx.showToast({title: "服务器异常了",icon: 'none',duration: 2000});}});}}};
</script>
<style>.ppf_item{padding: 0rpx 0rpx 0rpx 0rpx;}.block__title {margin: 0;font-weight: 400;font-size: 14px;color: rgba(69,90,100,.6);padding: 40rpx 30rpx 20rpx;}.button_up_blank{height: 40rpx;}.block__bottom{height: 180rpx;}.fee-last {margin-bottom: 200upx;}.cu-btn.lgplus {padding: 0 20px;font-size: 18px;height: 100upx;}.cu-btn.sharp {border-radius: 0upx;}.line-height {line-height: 100upx;}
</style>
import sheep from '@/sheep';
// #ifdef H5
import $wxsdk from '@/sheep/libs/sdk-h5-weixin';
// #endif
import { getRootUrl } from '@/sheep/helper';
import PayOrderApi from '@/sheep/api/pay/order';/*** 支付** @param {String} payment = ['wechat','alipay','wallet','mock']  	- 支付方式* @param {String} orderType = ['goods','recharge','groupon']  	- 订单类型* @param {String} id					- 订单号*/export default class SheepPay {constructor(payment, orderType, id) {this.payment = payment;this.id = id;this.orderType = orderType;this.payAction();}payAction() {const payAction = {WechatOfficialAccount: {wechat: () => {this.wechatOfficialAccountPay();},alipay: () => {this.redirectPay(); // 现在公众号可以直接跳转支付宝页面},wallet: () => {this.walletPay();},mock: () => {this.mockPay();}},WechatMiniProgram: {wechat: () => {this.wechatMiniProgramPay();},alipay: () => {this.copyPayLink();},wallet: () => {this.walletPay();},mock: () => {this.mockPay();}},App: {wechat: () => {this.wechatAppPay();},alipay: () => {this.alipay();},wallet: () => {this.walletPay();},mock: () => {this.mockPay();}},H5: {wechat: () => {this.wechatWapPay();},alipay: () => {this.redirectPay();},wallet: () => {this.walletPay();},mock: () => {this.mockPay();}},};return payAction[sheep.$platform.name][this.payment]();}// 预支付prepay(channel) {return new Promise(async (resolve, reject) => {let data = {id: this.id,channelCode: channel,channelExtras: {}};// 特殊逻辑:微信公众号、小程序支付时,必须传入 openidif (['wx_pub', 'wx_lite'].includes(channel)) {const openid = await sheep.$platform.useProvider('wechat').getOpenid();// 如果获取不到 openid,微信无法发起支付,此时需要引导if (!openid) {this.bindWeixin();return;}data.channelExtras.openid = openid;}// 发起预支付 API 调用PayOrderApi.submitOrder(data).then((res) => {// 成功时res.code === 0 && resolve(res);// 失败时if (res.code !== 0 && res.msg.indexOf('无效的openid') >= 0) {// 特殊逻辑:微信公众号、小程序支付时,必须传入 openid 不正确的情况if (res.msg.indexOf('无效的openid') >= 0 // 获取的 openid 不正确时,或者随便输入了个 openid|| res.msg.indexOf('下单账号与支付账号不一致') >= 0) { // https://developers.weixin.qq.com/community/develop/doc/00008c53c347804beec82aed051c00this.bindWeixin();}}});});}// #ifdef H5// 微信公众号 JSSDK 支付async wechatOfficialAccountPay() {let { code, data } = await this.prepay('wx_pub');if (code !== 0) {return;}const payConfig = JSON.parse(data.displayContent);$wxsdk.wxpay(payConfig, {success: () => {this.payResult('success');},cancel: () => {sheep.$helper.toast('支付已手动取消');},fail: (error) => {if (error.errMsg.indexOf('chooseWXPay:没有此SDK或暂不支持此SDK模拟') >= 0) {sheep.$helper.toast('发起微信支付失败,原因:可能是微信开发者工具不支持,建议使用微信打开网页后支付');return}this.payResult('fail');},});}// 浏览器微信 H5 支付 TODO 芋艿:待接入async wechatWapPay() {const { error, data } = await this.prepay();if (error === 0) {const redirect_url = `${getRootUrl()}pages/pay/result?id=${this.id}&payment=${this.payment}&orderType=${this.orderType}`;location.href = `${data.pay_data.h5_url}&redirect_url=${encodeURIComponent(redirect_url)}`;}}// 支付链接  TODO 芋艿:待接入async redirectPay() {let { error, data } = await this.prepay();if (error === 0) {const redirect_url = `${getRootUrl()}pages/pay/result?id=${this.id}&payment=${this.payment}&orderType=${this.orderType}`;location.href = data.pay_data + encodeURIComponent(redirect_url);}}// #endif// 微信小程序支付async wechatMiniProgramPay() {// let that = this;let { code, data } = await this.prepay('wx_lite');if (code !== 0) {return;}// 调用微信小程序支付const payConfig = JSON.parse(data.displayContent);uni.requestPayment({provider: 'wxpay',timeStamp: payConfig.timeStamp,nonceStr: payConfig.nonceStr,package: payConfig.packageValue,signType: payConfig.signType,paySign: payConfig.paySign,success: (res) => {this.payResult('success');},fail: (err) => {if (err.errMsg === 'requestPayment:fail cancel') {sheep.$helper.toast('支付已手动取消');} else {this.payResult('fail');}},});}// 余额支付async walletPay() {const { code } = await this.prepay('wallet');code === 0 && this.payResult('success');}// 模拟支付async mockPay() {const { code } = await this.prepay('mock');code === 0 && this.payResult('success');}// 支付宝复制链接支付  TODO 芋艿:待接入async copyPayLink() {let that = this;let { error, data } = await this.prepay();if (error === 0) {// 引入showModal 点击确认 复制链接;uni.showModal({title: '支付宝支付',content: '复制链接到外部浏览器',confirmText: '复制链接',success: (res) => {if (res.confirm) {sheep.$helper.copyText(data.pay_data);}},});}}// 支付宝支付  TODO 芋艿:待接入async alipay() {let that = this;const { error, data } = await this.prepay();if (error === 0) {uni.requestPayment({provider: 'alipay',orderInfo: data.pay_data, //支付宝订单数据success: (res) => {that.payResult('success');},fail: (err) => {if (err.errMsg === 'requestPayment:fail [paymentAlipay:62001]user cancel') {sheep.$helper.toast('支付已手动取消');} else {that.payResult('fail');}},});}}// 微信支付  TODO 芋艿:待接入async wechatAppPay() {let that = this;let { error, data } = await this.prepay();if (error === 0) {uni.requestPayment({provider: 'wxpay',orderInfo: data.pay_data, //微信订单数据(官方说是string。实测为object)success: (res) => {that.payResult('success');},fail: (err) => {err.errMsg !== 'requestPayment:fail cancel' && that.payResult('fail');},});}}// 支付结果跳转,success:成功,fail:失败payResult(resultType) {sheep.$router.redirect('/pages/pay/result', {id: this.id,orderType: this.orderType,payState: resultType});}// 引导绑定微信bindWeixin() {uni.showModal({title: '微信支付',content: '请先绑定微信再使用微信支付',success: function (res) {if (res.confirm) {sheep.$platform.useProvider('wechat').bind();}},});}}export function getPayMethods(channels) {const payMethods = [{icon: '/static/img/shop/pay/wechat.png',title: '微信支付',value: 'wechat',disabled: true,},{icon: '/static/img/shop/pay/alipay.png',title: '支付宝支付',value: 'alipay',disabled: true,},{icon: '/static/img/shop/pay/wallet.png',title: '余额支付',value: 'wallet',disabled: true,},{icon: '/static/img/shop/pay/apple.png',title: 'Apple Pay',value: 'apple',disabled: true,},{icon: '/static/img/shop/pay/wallet.png',title: '模拟支付',value: 'mock',disabled: true,}];const platform = sheep.$platform.name// 1. 处理【微信支付】const wechatMethod = payMethods[0];if ((platform === 'WechatOfficialAccount' && channels.includes('wx_pub'))|| (platform === 'WechatMiniProgram' && channels.includes('wx_lite'))|| (platform === 'App' && channels.includes('wx_app'))) {wechatMethod.disabled = false;}wechatMethod.disabled = false; // TODO 芋艿:临时测试// 2. 处理【支付宝支付】const alipayMethod = payMethods[1];if ((platform === 'WechatOfficialAccount' && channels.includes('alipay_wap'))|| platform === 'WechatMiniProgram' && channels.includes('alipay_wap')|| platform === 'App' && channels.includes('alipay_app')) {alipayMethod.disabled = false;}// 3. 处理【余额支付】const walletMethod = payMethods[2];if (channels.includes('wallet')) {walletMethod.disabled = false;}// 4. 处理【苹果支付】TODO 芋艿:未来接入// 5. 处理【模拟支付】const mockMethod = payMethods[4];if (channels.includes('mock')) {mockMethod.disabled = false;}return payMethods;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/743540.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

并发支持库(4)-条件变量

条件变量允许多个线程之间的交流。它可以阻塞某个线程&#xff0c;直到另一个线程的提醒再继续&#xff0c;这是通过关联一个互斥体来实现的。 本文章的代码库&#xff1a; https://gitee.com/gamestorm577/CppStd condition_variable condition_variable是和mutex一起使用…

使用Nginx进行负载均衡

什么是负载均衡 Nginx是一个高性能的开源反向代理服务器&#xff0c;也可以用作负载均衡器。通过Nginx的负载均衡功能&#xff0c;可以将流量分发到多台后端服务器上&#xff0c;实现负载均衡&#xff0c;提高系统的性能、可用性和稳定性。 如下图所示&#xff1a; Nginx负…

HDOJ 2036

改革春风吹满地 Problem Description “ 改革春风吹满地, 不会AC没关系; 实在不行回老家&#xff0c; 还有一亩三分地。 谢谢!&#xff08;乐队奏乐&#xff09;” 话说部分学生心态极好&#xff0c;每天就知道游戏&#xff0c;这次考试如此简单的题目&#xff0c;也是云里雾…

如何注册Devin-首个全自主AI软件工程师

最近devin大火&#xff0c;具体的就不说了&#xff0c;大家应该都知道&#xff0c;写代码非常nb&#xff0c;这里说一下devin的注册方式&#xff0c;目前devin的内测已经开启。 官网https://www.cognition-labs.com/blog注册网址Your reliable AI software engineerhttps://pr…

一文扫荡,12个可视化图表js库,收藏备用。

一、什么是可视化图表 可视化图表是通过图形化的方式将数据可视化展示出来的一种方式。它能够将复杂的数据以直观、易懂的形式呈现给用户&#xff0c;帮助用户更好地理解和分析数据。 可视化图表可以包括各种类型的图表&#xff0c;如线形图、柱状图、饼图、散点图、雷达图等。…

查看docker安装MySQL版本

要查看Docker中安装的MySQL版本&#xff0c;您可以按照以下步骤操作&#xff1a; 首先确保您有一个正在运行的MySQL Docker容器。如果尚未启动MySQL容器&#xff0c;请使用类似下面的命令启动它&#xff08;假设已经从Docker Hub拉取了镜像&#xff09;&#xff1a; docker run…

L2-034: 口罩发放(Python)

为了抗击来势汹汹的 COVID19 新型冠状病毒&#xff0c;全国各地均启动了各项措施控制疫情发展&#xff0c;其中一个重要的环节是口罩的发放。 某市出于给市民发放口罩的需要&#xff0c;推出了一款小程序让市民填写信息&#xff0c;方便工作的开展。小程序收集了各种信息&…

centos命令history设置记录10000行

今天在操作服务器的时候&#xff0c;用history查看操作记录的时候&#xff0c;发现只能查看10条&#xff0c;这样不行啊&#xff0c;我想查看所有人对服务器操作的命令。 [rootbogon ~]# history解决办法&#xff1a; #1、找到/etc/profile文件中的histsize 把10改成10000 […

【django framework】ModelSerializer+GenericAPIView,如何在提交前修改某些字段值

【django framework】ModelSerializerGenericAPIView&#xff0c;如何在提交前修改某些字段值 我们经常会遇到下面这种情况&#xff1a; 序列化器用的是ModelSerializer&#xff0c;写视图的时候继承的是generics.CreateAPIView。现在我想在正式提交到数据库(perform_create)之…

Windows kafka 简单集群搭建

Windows kafka 简单集群搭建 文章目录 Windows kafka 简单集群搭建1.环境说明2.Zookeeper集群搭建2.1 ZooKeeper下载2.2 ZooKeeper安装2.2.1 解压zookeeper-3.4.8.tar.gz2.2.2 进入conf目录下&#xff0c;复制zoo_sample.cfg为zoo.cfg2.2.3 修改zoo.cfg文件2.2.4 生成myid文件2…

加速 PyTorch 模型预测常见方法梳理

目录 1. 使用 GPU 加速 2. 批量推理 3. 使用半精度浮点数 (FP16) 4. 禁用梯度计算 5. 模型简化与量化 6. 使用 TorchScript 7. 模型并行和数据并行 结论 在使用 PyTorch 进行模型预测时&#xff0c;可以通过多种方法来加快推理速度。以下是一些加速模型预测的常用方法&…

24GB内存就能跑7B参数大模型?全新训练策略GaLore助你突破内存瓶颈

训练大型语言模型&#xff0c;内存总是个大问题。 权重啊、优化器状态啊&#xff0c;都得吃内存&#xff0c;而且吃得还不少。 为了省内存&#xff0c;有人就想出了一些招儿&#xff0c;比如低秩适应&#xff08;LoRA&#xff09;&#xff0c;就是给预训练权重添点儿可训练的…

基于YOLOv8深度学习的木薯病害智能诊断与防治系统【python源码+Pyqt5界面+数据集+训练代码】深度学习实战

《博主简介》 小伙伴们好&#xff0c;我是阿旭。专注于人工智能、AIGC、python、计算机视觉相关分享研究。 ✌更多学习资源&#xff0c;可关注公-仲-hao:【阿旭算法与机器学习】&#xff0c;共同学习交流~ &#x1f44d;感谢小伙伴们点赞、关注&#xff01; 《------往期经典推…

将内容写入文件并下载文件

这里写自定义目录标题 import saveAs from file-saver; // 获取时间 年月日时分秒 const getTimeInfo () > {return new Date().toLocaleString().replace(/\//g, ).replace(/:/g, ).replace(/ /g, ) };const getRandom () > {return (Math.random() * 10).toFixed(0);…

基于C++的一种字符串切分方法及示例代码

一、概述 在 Java 和 python 中&#xff0c;都有实现字符串切分的方法&#xff0c; 如split() &#xff0c;使用起来较为方便&#xff0c;但是在标准的 C 中&#xff0c;却没有内置的 split() 方法。 我们可以使用标准库中的一些函数和方法来实现字符串的切分&#xff0c;这里…

Android 实现 子线程 主线程 切换

Android 子线程切换到主线程 在 Android 开发中&#xff0c;我们经常需要在子线程中执行一些耗时操作&#xff0c;例如网络请求或者数据库操作。然而&#xff0c;由于 Android 的主线程&#xff08;也称为 UI 线程&#xff09;负责处理用户交互和更新界面&#xff0c;所以我们不…

【Java系列】OOM 时,JVM 堆栈信息保存和分析

一、前言 在日常开发中&#xff0c;即使代码写得再谨慎&#xff0c;免不了还是会发生各种意外的事件&#xff0c;比如服务器内存突然飙高&#xff0c;又或者发生内存溢出(OOM)。当发生这种情况时&#xff0c;我们怎么去排查&#xff0c;怎么去分析原因呢&#xff1f; 一般遇到…

前端开发小技巧【Vue篇】 - 样式穿透 + 绑定变量

前言 样式穿透 Vue都是通过深度选择器来样式穿透的。当我们在写项目的时候&#xff0c;经常会导入第三方库&#xff0c;有些特殊的情况&#xff0c;就是在导入第三方库后&#xff0c;呈现的样式并不是我们想要的样式&#xff0c;所以我们需要对第三方的样式进行修改&#xff1…

Java毕业设计 基于SSM jsp房屋租赁系统 房屋出租系统

Java毕业设计 基于SSM jsp房屋租赁系统 房屋出租系统 SSM jsp 房屋租赁系统 房屋出租系统 功能介绍 用户&#xff1a;首页 图片轮播 搜索 登录注册 新闻公告 新闻公告详情 装修广告 热门房源 房源详情 合租 整租 商业办公 普通民宅 酒店式公寓 全部房源 留言交流 发布帖子 模…

Linux下platform设备信息代码框架实现

一. 简介 前面一篇文章简单学习了Linux内核中 platform设备代码。文章地址如下&#xff1a; Linux内核中platform设备简介-CSDN博客 本文来学习如何编写 platform设备代码框架&#xff0c;为了后面学习 Linux下platform驱动开发。 二. Linux下platform设备信息代码框架实现…