Skip to content

Commit

Permalink
Merge pull request #20 from JasonBoy/paymenttest
Browse files Browse the repository at this point in the history
Payment APIs Refinements
  • Loading branch information
JasonBoy authored Mar 21, 2018
2 parents cf3c983 + 43d4c26 commit 8b2064d
Show file tree
Hide file tree
Showing 16 changed files with 3,452 additions and 1,348 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,5 @@ Gemfile
Gemfile.lock
_site/
package-lock.json
cert
cert
db_*.json
168 changes: 168 additions & 0 deletions demo/Order.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
'use strict';

const debug = require('debug')('wechat-Order');
const path = require('path');
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const isEmpty = require('lodash.isempty');

const adapter = new FileSync(path.join(__dirname, '../db_demo.json'));
const db = low(adapter);

const utils = require('../lib/utils');

db.defaults(
{
//our own system orders
orders: [],
//wechat unified orders
unifiedOrders: [],
//wechat notified order states
wechatOrders: [],
//refund
refundOrders: [],
//save wechat payment notify result
wechatNotifyOrders: [],
wechatNotifyRefunds: [],
}
).write();

/**
* A demo implementation for order & payment
*/
class Order {

constructor(options) {
this.payment = options.payment;
}

createOrder(info) {
const now = new Date;
const now2 = new Date;
const hour = now2.getHours();
const nowPlusTwoHours = now2.setHours(hour + 2);
const temp = utils.nonceStr();
const order = {
device_info: 'wechat_test_web',
body: `ORDER_测试_${temp}`,
detail: JSON.stringify({
"details_id": temp,
"goods_detail": [
{
"goods_id": "iphone6s_16G",
"wxpay_goods_id": "1001",
"goods_name": "iPhone6s 16G",
"quantity": 1,
"price": 528800,
"goods_category": "123456",
"body": "苹果手机"
},
]
}),
attach: '上海分店',
total_fee: '101',
spbill_create_ip: '127.0.0.1',
time_start: utils.simpleDate(now),
time_expire: utils.simpleDate(nowPlusTwoHours),
goods_tag: 'wx_test',
// notify_url: 'http://beautytest.yjyyun.com/payment/',
// product_id: '',
// limit_pay: '',
// openid: info.openId,
scene_info: JSON.stringify({
"id": "SH001",
"name": "上大餐厅",
"area_code": "200100",
"address": "广中路引力楼1楼"
})
};
Object.assign(order, info);
return this.payment.unifiedOrder(order)
.then(result => {
const requestData = Object.assign({id: result.requestData.out_trade_no}, result.requestData);
const responseData = Object.assign({id: result.responseData.out_trade_no}, result.responseData);
const hasOrder = db.get('orders')
.find({id: requestData.id})
.has('id')
.value();
if(hasOrder) {

} else {
db.get('orders')
.push(requestData)
.write();
db.get('unifiedOrders')
.push(responseData)
.write();
debug('add new order & unified order finished!');
}
return Promise.resolve(responseData);
})
.then(data => {
return this.payment.generateChooseWXPayInfo(data.prepay_id)
.then(chooseWXPayData => {
console.log('parsed data:', data);
console.log('WXpaydata data:', chooseWXPayData);
return Promise.resolve({
orderId: data.out_trade_no,
chooseWXPay: chooseWXPayData,
});
})
})
}

queryOrder (tradeNo) {
return this.payment.queryOrder({
out_trade_no: tradeNo
})
.then(result => {
const temp = Object.assign({id: result.responseData.out_trade_no}, result.responseData);
db.get('wechatOrders')
.push(temp)
.write();
debug('write wechat query order finished!');
return Promise.resolve(result);
})
}

updateNotifyResult(data) {
const order = db.get('wechatNotifiesOrders')
.find({id: data.out_trade_no})
.value();
if(!isEmpty(order)) {
if(order.processed) return;
//update existing order info
db.get('wechatNotifiesOrders')
.find({id: data.out_trade_no})
.assign(data)
.write();
return;
}
const temp = Object.assign({id: data.out_trade_no, processed: true}, data);
db.get('wechatNotifiesOrders')
.push(temp)
.write();
}

updateNotifyRefundResult(data) {
const order = db.get('wechatNotifyRefunds')
.find({id: data.out_trade_no})
.value();
if(!isEmpty(order)) {
if(order.processed) return;
//update existing order info
db.get('wechatNotifyRefunds')
.find({id: data.out_trade_no})
.assign(data)
.write();
return;
}
const temp = Object.assign({id: data.out_trade_no, processed: true}, data);
db.get('wechatNotifyRefunds')
.push(temp)
.write();
}

}

module.exports = Order;
165 changes: 124 additions & 41 deletions demo/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,38 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1.0, user-scalable=no">
<title>Wechat JSSDK DEMO</title>
<!--<script src="//res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>-->
<script src="//cdn.bootcss.com/zepto/1.1.6/zepto.min.js"></script>
<script src="/client.js"></script>
</head>
<body>
<p>点击右上角分享!</p>
<p><a href="{{ oauthUrl }}">OAuth</a></p>
<p><a href="{{ implicitOAuth }}">Implicit OAuth</a></p>
<p><a href="/oauth-cache">OAuth without new code</a></p>
<p><a id="choose-card" href="#">ChooseCard</a></p>
<p><a id="open-card" href="#">OpenCard</a></p>
<h5>点击右上角分享!</h5>
<h5>=====OAuth 网页授权=====</h5>
<p><a id="oauth-1" href="{{ oauthUrl }}">OAuth 用户信息授权</a></p>
<p><a id="oauth-2" href="{{ implicitOAuth }}">Implicit OAuth 静默授权</a></p>
<p><a id="oauth-3" href="/oauth-cache">OAuth without new code 用缓存code直接拿用户信息</a></p>
<h5>=====CARD 卡券=====</h5>
<p><a id="choose-card" href="#">ChooseCard 选择卡券并打开</a></p>
<p><a id="open-card" href="#">OpenCard 打开卡券</a></p>
<p><a id="add-card" href="#">AddCard 添加卡券</a></p>
<h5>=====Payment 支付=====</h5>
<p><a id="create-order" href="#">UnifiedOrder 创建订单</a></p>
<p><a id="pay-now" href="#">PayNow 微信支付</a></p>
<p><a id="query-order" href="#">QueryOrder 查询上面创建的订单</a></p>
<script type="text/javascript">
var config = {
"appId": "wxfc9c5237ebf480aa",
success: function(w) {
const config = {
// "appId": "wxfc9c5237ebf480aa",
"appId": "wxee7f6cc5d88ceae6",
success: function (w) {
console.log('success');
// var w = this;
var img = 'http://pic1.ooopic.com/uploadfilepic/shiliang/2009-10-05/OOOPIC_00cyl_20091005e2c6eb1c889e342e.jpg';
const img = 'http://pic1.ooopic.com/uploadfilepic/shiliang/2009-10-05/OOOPIC_00cyl_20091005e2c6eb1c889e342e.jpg';
//sugar method
w.shareOnMoment({
title: 'test title',
type: 'link',
success: function() {
success: function () {
console.log('share on moment success');
},
cancel: function() {
cancel: function () {
console.log('share on moment canceled');
},
imgUrl: img
Expand All @@ -40,58 +46,135 @@
title: 'test title',
type: 'link',
desc: 'share description',
success: function() {
success: function () {
console.log('share on chat success');
},
cancel: function() {
cancel: function () {
console.log('share on chat canceled');
},
imgUrl: img
});
},
error: function(err) {
error: function (err) {
console.error(err)
},
debug: true
};
$.ajax({
type: 'GET',
url: '/get-signature',
dataType: 'json',
data: {
url: location.href
},
success: function(data) {

const demoCardId = 'py5F1wWko7pRFaXBMGJD1vK6PdjE';

window.fetch(`/get-signature?url=${encodeURIComponent(location.href)}`, {
credentials: "same-origin",
})
.then(res => res.json())
.then(data => {
config.nonceStr = data.nonceStr;
config.signature = data.signature;
config.timestamp = data.timestamp;
config.jsApiList = ['hideMenuItems', 'onMenuShareTimeline', 'chooseCard', 'addCard', 'openCard'];
config.jsApiList = ['hideMenuItems', 'onMenuShareTimeline', 'chooseCard', 'addCard', 'openCard', 'chooseWXPay'];
window.wechatObj = new window.WechatJSSDK(config);
}
});
$('#choose-card').on('click', function(e) {
});

document.getElementById('choose-card').addEventListener('click', (e) => {
e.preventDefault();
$.ajax({
type: 'GET',
url: '/choose-card',
success: function(data) {
window.fetch(`/choose-card?cardId=${demoCardId}`, {
credentials: "same-origin",
})
.then(res => res.json())
.then(data => {
window.wechatObj.callWechatApi('chooseCard', Object.assign(data, {
success: function (res) {
success: res => {
console.log(res.cardList);
const list = JSON.parse(res.cardList);
//open the selected card
window.fetch(`/decode-card-code?encryptCode=${list[0].encrypt_code}`)
.then(res => res.json())
.then(data => {
window.wechatObj.callWechatApi('openCard', {
cardList: [{
cardId: demoCardId,
code: data.code,
}],
})
});
}
}));
}
})
});
$('#open-card').on('click', function (e) {
});
}, false);

document.getElementById('open-card').addEventListener('click', (e) => {
e.preventDefault();
window.wechatObj.callWechatApi('openCard', {
cardList: [{
cardId: 'pVI6xjmqRLg8y58MRpDQQangdmuY',
code: 'xxx',
cardId: demoCardId,
code: '739456048118',
}],
})
});
}, false);

document.getElementById('add-card').addEventListener('click', (e) => {
e.preventDefault();
window.fetch(`/get-card-ext?cardId=${demoCardId}`, {
credentials: "same-origin",
})
.then(res => res.json())
.then(data => {
window.wechatObj.callWechatApi('addCard', {
cardList: [{
cardId: demoCardId,
cardExt: data.data,
}],
success: function (res) {
const cardList = res.cardList; // 添加的卡券列表信息
console.log(typeof cardList, cardList);
}
})
});

}, false);

let wxData = {};

document.getElementById('create-order').addEventListener('click', (e) => {
e.preventDefault();
window.fetch(`/create-order`, {
credentials: "same-origin",
})
.then(res => res.json())
.then(data => {
wxData = data;
alert(JSON.stringify(data));
// window.wechatObj.callWechatApi('chooseWXPay', Object.assign({
// success: res => {
// console.log(res);
// }
// }, data));
});

}, false);
document.getElementById('query-order').addEventListener('click', (e) => {
e.preventDefault();
window.fetch(`/query-order`, {
credentials: "same-origin",
})
.then(res => res.json())
.then(data => {
console.log(data);
alert(JSON.stringify(data));
});

}, false);

document.getElementById('pay-now').addEventListener('click', (e) => {
e.preventDefault();
window.wechatObj.callWechatApi('chooseWXPay', Object.assign({
success: res => {
console.log(res);
}
}, wxData));

}, false);

</script>
</body>
</html>
Loading

0 comments on commit 8b2064d

Please sign in to comment.