thinkphp5使用native在PC网页端实现微信扫码支付

背景

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

后端

返回的是一个二维码的地址,
前端可以通过npm下载qrcode.vue第三方包来讲地址转换成二维码,参考文章:https://blog.csdn.net/weixin_61769998/article/details/132045842?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22132045842%22%2C%22source%22%3A%22weixin_61769998%22%7D。

	public function unifiedordersaas($total){
        $notifyUrl = '';//支付成功异步回调地址
        // $orderName = '订单名称';
        $total_amount = $total * 100;
        $unified = array(
            'appid' => '',
            'attach' => 'pay',             //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
            'body' => '',
            'mch_id' => '',
            'nonce_str'=> time(),
            'notify_url'=>$notifyUrl,//你的回调地址
            'out_trade_no'=> create_guid(),
            'spbill_create_ip'=> request()->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='.''; // 商户号秘钥
        $unified['sign'] = strtoupper(md5($str));
        $responseXml = $this->curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder',ToXml($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 json($codeUrl[0]);
    }
    
    // curlPost($param)是接收微信服务器数据的函数
    public 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;
    }

你可能感兴趣的:(微信)