前端页面,正常下单,发起请求,把所需要的数据传入后端。
<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//把所需要的数据传后后端
function buy(){
var data = {
total_fee:price,
body:goodsName,
openid:openid
};
$.ajax({
type:'post',
urrl,'/buy',
data,data,
dataTyle:'json',
success:function(res){
console.log(res);
if(res == true){
WeixinJSBridge.invoke(
'getBrandWCPayRequest', <?= $json ?>,
function(res){
if(res.err_msg == "get_brand_wcpay_request:ok" ) {//成功
//这儿可以直接跳转到首页
// 使用以上方式判断前端返回,微信团队郑重提示:
// res.err_msg将在用户支付成功后返回
// ok,但并不保证它绝对可靠。
}else{//走失败
}
}
);
}
}
})
}
</script>
//config.php
<?php
$result = array(
'app_id' => '',
'secret' => '',
'response_type' => 'array',
'token' => '',
'oauth' => [
'only_wechat_browser' => false,
'scopes' => ['snsapi_userinfo'],
'callback' => '',
],
'log' => [
'level' => 'debug',
'permission' => 0777,
'file' => '/tmp/easywechat.log',
],
'mch_id' => '',//商户号
'key' => '',//API 密钥
'sandbox' => true, // 设置为 false 或注释则关闭沙箱模式
);
return $result;
?>
//控制器文件
<?php
namespace app\wechat\controller;
use app\BaseController;
use think\facade\Config;
use EasyWeChat\Factory;
use think\facade\View;
class Access extends BaseController{
private $_config;
public function __construct(){
$config = Config::get('wechat');
$this->_config = $config;
}
public function buy(){
$shopInfo = input('post.'); //前端传来的数据
$shopInfo['out_trade_no'] = ''; //订单号
$shopInfo['trade_type'] = 'JSAPI';
$shopInfo['notify_url'] = '/paySuccess'; //回调地址
$config = $this->_config;
$payment = Factory::payment($config);
$res = $payment->order->unify($shopInfo); //统一下单
$jssdk = $payment->jssdk; //生成jssdk
$json = $jssdk->bridgeConfig($res['prepay_id'],false); // 返回数组
View::assign('json',$json);
return true;
}
}
?>
//支付回调
public function paySuccess(){
$response = $app->handlePaidNotify(function ($message, $fail) {
if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
// 用户是否支付成功
if ($message['result_code'] === 'SUCCESS') {
//修改订单状态
} elseif ($message['result_code'] === 'FAIL') {// 用户支付失败
// 用户支付失败
}
} else {
return $fail('通信失败,请稍后再通知我');
}
return true; // 返回处理完成
});
}