


Three tips to teach you how to implement WeChat gift tipping function (full code)
Jul 25, 2018 pm 02:36 PMThe content in the tutorial does not realize which post or article has received the payment. Of course, my site has implemented it, you can try it. It’s been a while since I’ve written a practical article. Today I’ll share one, using yii2 houjs yii2-wx to implement the gift-sending function on WeChat.
Let’s take a look at the renderings first
To put it simply, after clicking the "Send Gift" button, a pop-up box will appear, which contains There are many gifts. After clicking on a gift, the pop-up box refreshes and a QR code appears. Scan the code on WeChat to pay.
Of course, the money will be entered into the member's personal account and then withdrawn.
Why do you want to do such a function? To be honest, I really didn’t think about getting much from this. It is more of an incentive. If you share valuable articles in our learning community, you are very likely to receive a gift from me.
Okay, let’s talk about functions. There are several functions.
Creating a data table structure (gifts and gift-delivery logs)
-
Use houjs to complete the front-end pop-up box
Use yii2-wx to implement payment QR code
-
Add account functions for users
Enterprises using yii2-wx can pay in small change and the console mode of yii2 can realize the payment function for users (payment is made if it is greater than or equal to 2 yuan).
Let me check it out, it’s full of useful information. start.
Data table structure
Since it is giving gifts, it naturally includes a gift table and a log table for giving gifts. I plan as follows.
Gift table gift
Gift log table gift_log
For the gift_log table, lang_id is not required. This field is added here for statistical convenience.
Overall idea
The overall logic for users to send gifts is as follows
Click "Send Gift" to interact with the background to obtain this community gift list.
After obtaining the data, use the jsmart engine to render the html code of the specific gift.
Use modal to put the gift list into the pop-up box.
Click on the gift to interact with the background, and the background will generate a QR code and return it.
Users scan the QR code to pay.
Payment successful.
Get the gift list
Next we use houjs to build the front-end function. Regarding the use of houjs, you can go to the community to view the portal. We mainly use its modal pop-up box. Helper and jsmart template engine.
First specify a button
<button class="ui green button" id="giftBtn" data-url="<?= Url::to(['/gift/list','id'=>$lang->id]);?>"> <i class="share icon"></i>送禮物 </button>
data-url represents the route used to obtain the gift list, and do a click event processing for the button
requirejs(['mods/modal','jSmart'],function(modal,jSmart){ $('#giftBtn').click(function(){ var url = $(this).attr('data-url'); $.getJSON(url,{},function(d){ if(d.result === 'ok'){ // d.data }else{ modal.msg(d.message); } }); }); })
Initiated a request to obtain Gift list, error message if failed.
Next we create a new GiftController.php and define the list action.
public function actionList($id){ Yii::$app->response->format = 'json'; try { $data = Gift::find()->where(['lang_id'=>$id])->asArray()->all(); return ['result'=>'ok','data'=>$data]; }catch(Exception $e){ return ['result'=>'fail','message'=>$e->getMessage()]; } }
From here we know that d.data in the data obtained after clicking the button is the gift list of this community.
After the front desk gets the gift list, use jsmart to convert the data into html code. To do this, we need to make a jsmart template first and add this template to the gift button page.
<script id="giftTpl" type="text/x-jsmart-tmpl"> <p class="gifts-box"> <p class="gifts"> {foreach $data as $key=>$gift} <a href=""> <p class="gift-icon"><img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/377/959/949/1532500396901059.jpg" class="lazy" src='{$gift.icon}'/ alt="Three tips to teach you how to implement WeChat gift tipping function (full code)" ></p> <p class="gift-name">{$gift.name}</p> </a> {/foreach} </p> </p> </script>
The general meaning of this template is that the data in d.data mentioned above is circulated, each gift is placed in tag a, and then we add the js code to obtain the gift list from the background, as follows.
requirejs(['mods/modal','jSmart'],function(modal,jSmart){ $('#giftBtn').click(function(){ var url = $(this).attr('data-url'); $.getJSON(url,{},function(d){ if(d.result === 'ok'){ var tplText = $('#giftTpl').html(); var compiledTemplate = new jSmart(tplText); var output = compiledTemplate.fetch(d); modal.alert(output,{ inPage:false, title:'送禮物', size:'tiny' }); }else{ modal.msg(d.message); } }); }); })
Perform template rendering, and it’s time for us to see the effect.
I like it very much, using yii2 and houjs's modal&jsmart to complete the gift list function. Next we have to do an important thing, interact with the backend and get the payment QR code.
Get the payment QR code
In this chapter we use the yii2-wx extension to implement the WeChat payment function. The idea is to obtain the payment QR code after clicking on the gift.
Before proceeding, we optimize the js method in the previous step and put the code into a separate js module. In houjs, it is recommended to put the business js code in houjs/js/modules, as follows
define(function(require,exports,modules){ var modal = require('mods/modal'); var jSmart = require('jSmart'); exports.list = function(){ $('#giftBtn').click(function(){ var url = $(this).attr('data-url'); $.getJSON(url,{},function(d){ if(d.result === 'ok'){ var tplText = $('#giftTpl').html(); var compiledTemplate = new jSmart(tplText); var output = compiledTemplate.fetch(d); modal.alert(output,{ inPage:false, title:'送禮物給作者', size:'tiny' }); }else{ modal.msg(d.message); } }); }); }; });
Therefore, the js code call to obtain the gift list becomes simple, as follows
requirejs(['modules/gift'],function(gift){ gift.list(); })
In the future, the js code for gift can be placed in houjs/js/modules/gift.js.
Okay, let’s talk about this part of the topic. How to obtain the payment QR code?
My idea is as follows: After the user clicks on each gift, he initiates a get request to the server. This request contains the ID of the gift. After receiving it in the background, a gift log is generated. It communicates with the WeChat server to obtain the payment QR code, returns it to the browser, and renders the QR code in the frontend.
Just do it.
First add the gift list, the a link of each gift, as follows
<script id="giftTpl" type="text/x-jsmart-tmpl"> <p class="gifts-box"> <p class="gifts"> {foreach $data as $key=>$gift} <a class="_get_qrcode" href="javascript:;" data-url="<?= Url::to(['/gift/qrcode']);?>?id={$gift.id}"> <p class="gift-icon"><img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/377/959/949/1532500396901059.jpg" class="lazy" src='{$gift.icon}'/ alt="Three tips to teach you how to implement WeChat gift tipping function (full code)" ></p> <p class="gift-name">{$gift.name}</p> </a> {/foreach} </p> </p> </script>
We set 3 attributes for the a link of each gift
class="_get_qrcode" 一個類,這個類并不起到樣式作用,主要是為js監(jiān)聽此標(biāo)簽使用。
href="javascript:;" 防止點擊跳轉(zhuǎn)
data-url 點擊連接后,js函數(shù)將根據(jù)data-url提供的地址發(fā)起請求
接下來我們做一個js方法實現(xiàn)a鏈接點擊的監(jiān)聽,如下
// houjs/js/modules/gift.js define(function(require,exports,modules){ var modal = require('mods/modal'); var jSmart = require('jSmart'); ..... /** * 獲取某一個禮物的支付二維碼 */ exports.qrcode = function(){ $('._get_qrcode').click(function(){ var url = $(this).attr('data-url'); $.getJSON(url,{},function(d){ if(d.result === 'ok'){ $('#payQrcode') .html("<img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/377/959/949/1532500396901059.jpg" class="lazy" style="max-width:90%"+d.qrcode+"'/ alt="Three tips to teach you how to implement WeChat gift tipping function (full code)" >"); }else{ modal.msg(d.message); } }); }); }; });
有一點要說明,因此禮物列表是在頁面dom渲染后加入的html代碼,因此如果想讓禮物列表的a鏈接被監(jiān)聽,在獲取禮物列表成功后需要調(diào)用exports.qrcode()函數(shù)進(jìn)行監(jiān)聽,如下
// houjs/js/modules/gift.js define(function(require,exports,modules){ var modal = require('mods/modal'); var jSmart = require('jSmart'); exports.list = function(){ $('#giftBtn').click(function(){ var url = $(this).attr('data-url'); $.getJSON(url,{},function(d){ if(d.result === 'ok'){ .... exports.qrcode(); }else{ modal.msg(d.message); } }); }); }; /** * 獲取某一個禮物的支付二維碼 */ exports.qrcode = function(){ .... }; });
此刻用戶點擊了禮物的a鏈接,gift.qrcode()方法開始運作,請求達(dá)到了yii2的gift/qrcode動作,我寫了如下代碼。
// yii2 GiftController/actionQrcode <?php namespace app\controllers; use app\models\Gift; use app\models\GiftLog; use yii\helpers\Url; use abei2017\wx\Application; use Da\QrCode\QrCode; use Yii; use yii\base\Exception; class GiftController extends NBase { .... public function actionQrcode($id){ Yii::$app->response->format = 'json'; try { $model = Gift::findOne($id); // order $order = new GiftLog(); $order->gift_id = $id; $order->user_id = Yii::$app->user->id; $order->created_at = time(); $order->number = 1; $order->money = $order->number*$model->price; $order->status = 'unpay'; $order->lang_id = $model->lang_id; if($order->save() == false){ throw new Exception(implode(',',$order->getFirstErrors())); } $out_trade_no = "gift-{$order->id}-".rand(1000,9999); $totalFee = $order->money*100; $conf = Yii::$app->params['wx']; $app = new Application(['conf'=>$conf['mp']]); $pay = $app->driver("mp.pay"); $attributes = [ 'body'=>"送禮物", 'detail'=>"{$model->name}", 'out_trade_no'=>$out_trade_no, 'total_fee'=>$totalFee, 'notify_url'=>Yii::$app->urlManager->createAbsoluteUrl(['/gift/notify']), 'product_id'=>'gift-'.$id ]; $native = $pay->native($attributes); $qrCode = (new QrCode($native['code_url']))->setSize(250)->setMargin(20); return ['result'=>'ok','qrcode'=>$qrCode->writeDataUri()]; }catch(Exception $e){ return ['result'=>'fail','message'=>$e->getMessage()]; } } }
首先要說明的是上述代碼沒有問題,但如果上線還是要處理細(xì)節(jié)的。
在actionQrcode方法中我們做了3件事情
生成送禮物日志
調(diào)用yii2-wx生成支付二維碼
使用QrCode生成二維碼并傳給瀏覽器
這里使用的是yii2-wx提供的生成二維碼方法native,剩下的事情就是如何顯示這個二維碼。
為了讓用戶可以在支付前重新選擇禮物,本次并沒有選擇彈出二維碼,而是使用了禮物頁面替換的方法,如下圖
在禮物的右側(cè)我增加了一個p來存放二維碼,沒有選擇的時候用一些幫助來填充。這個二維碼的存放工作由gift.qrcode()方法實現(xiàn)
$('#payQrcode').html("<img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/377/959/949/1532500396901059.jpg" class="lazy" style="max-width:90%"+d.qrcode+"'/ alt="Three tips to teach you how to implement WeChat gift tipping function (full code)" >");
對應(yīng)的禮物列表模板也增加了支付區(qū)域
<script id="giftTpl" type="text/x-jsmart-tmpl"> <p class="gifts-box"> <p class="gifts"> {foreach $data as $key=>$gift} <a class="_get_qrcode" href="javascript:;" data-url="<?= Url::to(['/gift/qrcode']);?>?id={$gift.id}"> <p class="gift-icon"><img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/377/959/949/1532500396901059.jpg" class="lazy" src='{$gift.icon}'/ alt="Three tips to teach you how to implement WeChat gift tipping function (full code)" ></p> <p class="gift-name">{$gift.name}</p> </a> {/foreach} </p> <p id="payQrcode"> <h1>使用小提示</h1> <p> 點擊左側(cè)的小禮物后會出現(xiàn)支付二維碼,掃碼即送。 </p> </p> <p class="clear"></p> </p> </script>
好,看下效果。
用戶拿手機支付
當(dāng)用戶得到支付二維碼后必然是掃碼支付,接下來有兩個事情要做
yii2要處理微信支付結(jié)果通知,將此禮物日志設(shè)置為已經(jīng)支付。
瀏覽器上次禮物列表二維碼消失,提示支付成功。
先來處理結(jié)果通知,這個使用yii2-wx非常好實現(xiàn)。在GiftController中增加一個notify動作。
// GiftController.php <?php namespace app\controllers; use app\models\Gift; use app\models\GiftLog; use yii\data\ActiveDataProvider; use yii\helpers\Url; use abei2017\wx\Application; use Da\QrCode\QrCode; use Yii; use yii\base\Exception; class GiftController extends NBase { public $enableCsrfValidation = false; ...... public function actionNotify(){ $conf = Yii::$app->params['wx']; $app = new Application(['conf'=>$conf['mp']]); $pay = $app->driver("mp.pay"); $response = $pay->handleNotify(function($notify,$isSuccess){ if($isSuccess){ @list($_,$id,$_) = explode('-',$notify['out_trade_no']); $model = GiftLog::findOne($id); if($model->status == 'pay'){ return true; } $model->status = 'pay'; $model->paid_at = time(); $model->transaction_id = $notify['transaction_id']; $model->update(); return true; } }); return $response; } }
對上面的邏輯有幾點要注意,這也是我們用yii2-wx的時候要注意的。
關(guān)閉csrf驗證 主要是防止yii2將微信給我們的結(jié)果通知請求屏蔽掉。
在設(shè)置禮物日志已付款前要判斷下,如果已經(jīng)付款則返回true,這樣微信就不會再發(fā)請求。
現(xiàn)在我們搞定了回調(diào),看下效果。
不錯不錯
離成功越來越近了!接下來我們要解決一個問題,就是當(dāng)用戶支付后在瀏覽器上禮物列表的變化,我希望二維碼消失同時出現(xiàn)一個支付成功的頁面。
我需要一個輪詢,那么開始吧,為此我在gift.js中增加一個輪詢功能,這個功能在渲染出二維碼后被觸發(fā)。
//gift.js exports.askIsPay = function(id){ var url = '/gift/is-pay.html'; $.getJSON(url,{id:id},function(d){ if(d.result === 'ok'){ $('#payQrcode').empty() .html("<h1>支付成功</h1><p>感謝您對作者的支持,他會知道您的名字以及打款。</p>"); }else{ setTimeout(function(){ exports.askIsPay(id) },3000); } }); }
每3秒詢問一次服務(wù)器上gift/is-pay動作是否此送禮物日志已經(jīng)付款,當(dāng)然要告訴是哪個訂單,如果已經(jīng)付款則改變p#payQrcode的內(nèi)容,否則繼續(xù)調(diào)用exports.askIsPay(id)再一次詢問。一點注意的是我們在生成二維碼的時候需要服務(wù)器將此日志的id返回(這需要服務(wù)器的gift/qrcode動作返回此送禮物日志的ID),當(dāng)exports.askIsPay觸發(fā)時export.qrcode將其傳入。
... if(d.result === 'ok'){ $('#payQrcode').empty() .html("<img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/732/515/655/1532500450978915.jpg" class="lazy" style="max-width:90%"+d.qrcode+"'/ alt="Three tips to teach you how to implement WeChat gift tipping function (full code)" >"); exports.askIsPay(d.oId); }else{ modal.msg(d.message); } ...
當(dāng)然我們還要在服務(wù)器上新建一個控制器的動作。
// GiftController.php public function actionIsPay($id){ Yii::$app->response->format = 'json'; try { $model = GiftLog::findOne($id); if($model->status == 'unpay'){ throw new Exception('還沒有支付'); } return ['result'=>'ok']; }catch(Exception $e){ return ['result'=>'fail','message'=>$e->getMessage()]; } }
大功告成,看看效果。
小結(jié)
到此我們就完成了永不打賞禮物的全過程,算上部吧,下部我們將實現(xiàn)具體的打款到用戶賬號以及使用yii2-wx調(diào)用微信企業(yè)付款到零錢包接口實現(xiàn)錢到微信功能。
相關(guān)推薦:
The above is the detailed content of Three tips to teach you how to implement WeChat gift tipping function (full code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The login portal for the Douyin web version is https://www.douyin.com/. The login steps include: 1. Open the browser; 2. Enter the URL https://www.douyin.com/; 3. Click the "Login" button and select the login method; 4. Enter the account password; 5. Complete login. The web version provides functions such as browsing, searching, interaction, uploading videos and personal homepage management, and has advantages such as large-screen experience, multi-tasking, convenient account management and data statistics.

Copying comics is undoubtedly a treasure that cannot be missed. Here you can find basketball comics in various styles, from passionate and inspiring competitive stories to relaxed and humorous daily comedy. Whether you want to relive the classics or discover new works, copying comics can meet your needs. Through the authentic online reading portal provided by copy comics, you will bid farewell to the trouble of pirated resources, enjoy a high-definition and smooth reading experience, and can support your favorite comic authors and contribute to the development of authentic comics.

Choosing UC browser or QQ browser depends on your needs: 1. UC browser is suitable for users who pursue fast loading and rich entertainment functions; 2. QQ browser is suitable for users who need stability and seamless connection with Tencent products.

Combining the latest industry trends and multi-dimensional evaluation data in 2025, the following are the top ten comprehensive AI writing software recommendations, covering mainstream scenarios such as general creation, academic research, and commercial marketing, while taking into account Chinese optimization and localization services:

Nice Comics, an immersive reading experience platform dedicated to creating for comic lovers, brings together a large number of high-quality comic resources at home and abroad. It is not only a comic reading platform, but also a community that connects comic artists and readers and shares comic culture. Through simple and intuitive interface design and powerful search functions, NES Comics allows you to easily find your favorite works and enjoy a smooth and comfortable reading experience. Say goodbye to the long waiting and tedious operations, enter the world of Nice comics immediately and start your comic journey!

Frogman Comics has become the first choice for many comic lovers with its rich and diverse comic resources and convenient and smooth online reading experience. It is like a vibrant pond, with fresh and interesting stories constantly emerging, waiting for you to discover and explore. Frog Man comics cover a variety of subjects, from passionate adventures to sweet love, from fantasy and science fiction to suspense reasoning, no matter which genre you like, you can find your favorite works here. Its simple and intuitive interface design allows you to easily get started, quickly find the comics you want to read, and immerse yourself in the exciting comic world.

Here, you can enjoy the vast ocean of comics and explore works of various themes and styles, from passionate young man comics to delicate and moving girl comics, from suspenseful and brain-burning mystery comics to relaxed and funny daily comics, there is everything, and there is always one that can touch your heartstrings. We not only have a large amount of genuine comic resources, but also constantly introduce and update the latest works to ensure that you can read your favorite comics as soon as possible.

The latest official website of 2025b Announce is: https://www.marketwebb.co/zh-CN/join?ref=507720986&type=wenzi; Binance Exchange is a global cryptocurrency exchange that serves 180 countries and regions including North America, Europe, Taiwan, the Middle East, Hong Kong, and Malaysia. It provides more than 600 cryptocurrencies and has 270 million registered users worldwide.
