tp5使用native在PC网页端实现微信支付

背景

我们在开发中经常遇到在要在网页端唤起支付的情况,虽然很多时候是在微信浏览器中打开,可以直接用jsapi解决,但实际上有很多时候我们也是要在网页端实现调用二维码进行扫码支付的。这里使用thinkphp5作为案例进行开发。

代码

前端

前端用axios进行请求,大家也尽可使用ajax。

<html>
<head>native支付</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/static/vue.js"></script>
<script src="/static/axios.min.js"></script>
<body>
	<button onclick="pay()">native购买</button>
	<div id="code">
		<img src="" id="codeImg">
	</div>
	<script type="text/javascript">
		function pay(){
			let that=this;
			axios.post('/wechat/nativePay').then((r)=>{
				console.log(r.data)
				document.getElementById('codeImg').src="/"+r.data;
			})
		}
	</script>
</body>
</html>

后端

合理我返回的是一个二维码的地址,所以在前端是通过给img标签赋值的形式展示的。

function nativePay()
{
    $notifyUrl = '异步回调地址';//支付成功异步回调地址
    $orderName = '订单名称';
    $total_amount =1;
    $timestamp = time();
    $unified = array(
        'appid' => $this->config['appId'],
        'attach' => 'pay',             //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
        'body' => $orderName,
        'mch_id' => $this->config['mch_id'],
        'nonce_str'=> $this->createNoncestr(),
        'notify_url'=>$notifyUrl,//你的回调地址
        'out_trade_no'=> date('YmdHis').rand(1000, 9999),
        'spbill_create_ip'=> '<你的服务器ip>',
        'total_fee' => $total_amount ,       //单位 转为分
        'trade_type' => 'NATIVE',
    );
    $data = array_filter($unified);//过滤函数
    ksort($data);
    $str ='';
    foreach($data as $k=>$v) {
      $str.=$k.'='.$v.'&';
    }
    $str.='key='.$this->config['key'];
    $unified['sign'] = strtoupper(md5($str));
    $responseXml = $this->curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($unified));
    libxml_disable_entity_loader(true);
    $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
    if (false === $unifiedOrder) {
        die('parse xml error');
    }
    if ('SUCCESS' != $unifiedOrder->return_code) {
        die($unifiedOrder->return_msg);
    }
    if ('SUCCESS' != $unifiedOrder->result_code) {
        die($unifiedOrder->err_code);
    }
    $codeUrl = (array) ($unifiedOrder->code_url);
    if (!$codeUrl[0]) {
        exit('get code_url error');
    }
    $qrcodeImg=$this->code($codeUrl[0]);
    return $qrcodeImg;
  }

最终效果

在这里插入图片描述
点击native购买按钮后会弹出支付二维码

其他

其中涉及到几个函数code( u r l ) , c u r l P o s t ( url),curlPost( url),curlPost(param),createNoncestr()
code($url)是用来生成二维码的,TP5生成二维码可以看相关教程

curlPost($param)是接收微信服务器数据的函数,做过微信开发的应该都用过,为了方便大家这里也补充进来

function curlPost($url = '', $postData = '', $options = array())
{
  if (is_array($postData)) {
      $postData = http_build_query($postData);
  }
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
  if (!empty($options)) {
      curl_setopt_array($ch, $options);
  }
  //https请求 不验证证书和host
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  $data = curl_exec($ch);
  curl_close($ch);

  return $data;
}

createNoncestr()是用来生成随机字符的

public function createNoncestr($length =32){
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str ="";
    for ( $i = 0; $i < $length; $i++ ) {
    $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 PHP TP5 框架中实现微信支付功能,你需要完成以下几个步骤: 1. 注册微信商户平台账号,并在商户平台中创建应用,获取到商户ID和商户密钥。 2. 安装并配置 PHP SDK,可以使用官方提供的 SDK 或者选择第三方 SDK。 3. 编写支付接口,接收前端传来的订单信息,将订单信息传递给微信支付接口,生成预支付订单,并返回预支付订单信息给前端。 4. 前端根据预支付订单信息调起微信支付页面,用户完成支付后,微信将会回调你的支付回调接口。 5. 在支付回调接口中,验证微信回调的签名,防止恶意攻击,确认订单支付状态,更新订单状态等操作。 下面是一个简单的示例代码,仅供参考: ```php // 引入微信支付 SDK use EasyWeChat\Factory; // 创建支付对象 $config = [ 'app_id' => 'your-app-id', 'mch_id' => 'your-mch-id', 'key' => 'your-key', 'cert_path' => 'path/to/your/cert.pem', 'key_path' => 'path/to/your/key.pem', ]; $payment = Factory::payment($config); // 发起支付请求 $result = $payment->order->unify([ 'body' => 'test', 'out_trade_no' => 'your-order-id', 'total_fee' => 100, 'spbill_create_ip' => '127.0.0.1', 'notify_url' => 'your-notify-url', 'trade_type' => 'JSAPI', 'openid' => 'your-user-openid' ]); // 将预支付订单信息返回给前端 return $result; // 支付回调接口 $payment->notify(function ($notify, $successful) { // 验证签名 if (!$successful) { return 'fail'; } // 更新订单状态等操作 return 'success'; }); ``` 注意,以上代码仅为示例代码,具体实现需要根据你的业务需求进行调整。同时,为了确保支付安全,请务必仔细阅读微信支付开发文档,并遵循开发规范。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值